[LeetCode 342]Power of Four

2016-04-28  本文已影响0人  FTVBeginning

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example:Given num = 16, return true. Given num = 5, return false.
Follow up: Could you solve it without loops/recursion?

Method:

  1. Bitwise operation
  2. Pay attention to precedence of operators
  3. It can be found that the power of four are in 100,10000,1000000……binary form.
    (i)There is only 'one' '1' in the first place which means it will be 0 if we turn the '1' into '0'
    (ii)10,1000,100000 also follow this rule. The difference is the '1' only appears on odd position.
    4.The power of four must be larger than 0

C++:
class Solution {
public:
bool isPowerOfFour(int num) {
return(num>0 && (num&(num-1))==0 && (num&0x55555555)!=0);
}
};

上一篇 下一篇

猜你喜欢

热点阅读