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
来源: http://www.bubuko.com/infodetail-2222609.html