博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Find whether a given number is a power of 4 or not
阅读量:4150 次
发布时间:2019-05-25

本文共 834 字,大约阅读时间需要 2 分钟。

reference: 

Problem Definition:

Find whether a given number is a power of 4 or not.

Solution:

A number n is a power of 4 if following conditions are met.

a) There is only one bit set in the binary representation of n (or n is a power of 2)
b) The count of zero bits before the (only) set bit is even.

For example: 16 (10000) is power of 4 because there is only one bit set and count of 0s before the set bit is 4 which is even.

Code:

bool isPowerOfFour(unsigned int n){  int count = 0;   /*Check if there is only one bit set in n*/  if ( n && !(n&(n-1)) )  {     /* count 0 bits before set bit */     while(n > 1)     {       n  >>= 1;       count += 1;     }           /*If count is even then return true else false*/    return (count%2 == 0)? 1 :0;  }   /* If there are more than 1 bit set    then n is not a power of 4*/  return 0;}

转载地址:http://lexti.baihongyu.com/

你可能感兴趣的文章
引用还是指针?
查看>>
checkio-non unique elements
查看>>
checkio-medium
查看>>
checkio-house password
查看>>
checkio-moore neighbourhood
查看>>
checkio-the most wanted letter
查看>>
Redis可视化工具
查看>>
大牛手把手带你!2021新一波程序员跳槽季,全套教学资料
查看>>
JAVA自定义注解与通过反射去解析注解参数
查看>>
Effective Java学习(创建和销毁对象)之——通过私有化构造器强化不可实例化的能力...
查看>>
Effective Java学习(创建和销毁对象)之——消除过期对象引用
查看>>
Effective Java学习(泛型)之——消除非受检警告
查看>>
Effective Java学习(泛型)之——List列表优先于数组
查看>>
Effective Java学习(泛型)之——优先使用泛型化
查看>>
Effective Java学习(泛型)之——优先考虑泛型化方法
查看>>
Effective Java学习(方法)之——返回零长度的数组或者集合,而不是null
查看>>
Effective Java学习(通用程序设计)之——将局部变量的作用最小化
查看>>
Effective Java学习(通用程序设计)之——for-each循环优先于传统的for循环
查看>>
Effective Java学习(通用程序设计)之——如果需要精确的答案,请避免使用float和double...
查看>>
Effective Java学习(通用程序设计)之——如果其他类型更适合,请尽量避免使用字符串...
查看>>