[LeetCode] Power of Four
阿新 • • 發佈:2017-07-23
num integer int div code span 結果 write pow
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?
判斷一個數是否是4的冪,如果一個數是4的冪,則這個數的二進制的1在偶數位上。所以先判斷一個數是不是2的冪。然後判斷這個數與0x55555555按位與的結果,0x55555555使用十六位表示的數,它的奇數位上全是1,偶數位上全是0。
class Solution { public: bool isPowerOfFour(int num) { if (num <= 0) return false; if (!(num & (num - 1))) if (num & 0x55555555) return true; return false; } }; // 3 ms
相關題目:Power of Two
相關題目:Power of Three
[LeetCode] Power of Four