当前位置:   article > 正文

Find whether a given number is a power of 4 or not_n is a power of 4

n is a power of 4

reference: 

http://www.geeksforgeeks.org/find-whether-a-given-number-is-a-power-of-4-or-not/


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:

  1. bool isPowerOfFour(unsigned int n)
  2. {
  3. int count = 0;
  4. /*Check if there is only one bit set in n*/
  5. if ( n && !(n&(n-1)) )
  6. {
  7. /* count 0 bits before set bit */
  8. while(n > 1)
  9. {
  10. n >>= 1;
  11. count += 1;
  12. }
  13. /*If count is even then return true else false*/
  14. return (count%2 == 0)? 1 :0;
  15. }
  16. /* If there are more than 1 bit set
  17. then n is not a power of 4*/
  18. return 0;
  19. }


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/85171
推荐阅读
相关标签
  

闽ICP备14008679号