LeetCode 342 Power of Four
2016-10-12 12:49
323 查看
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的幂方。
这个问题用递归或者循环可以很容易就解决,但是题目的附加要求写着:不适用递归和循环。
因此,采用位运算的方法来解决。
0x55555555 <-> 1010101010101010101010101010101
Example:
Given num = 16, return true. Given num = 5, return false.
Follow up: Could you solve it without loops/recursion?
题目要求判断一个数是不是4的幂方。
这个问题用递归或者循环可以很容易就解决,但是题目的附加要求写着:不适用递归和循环。
因此,采用位运算的方法来解决。
class Solution { public: bool isPowerOfFour(int num) { if(num <= 0) return false; // 判断是否为正数 if(num&(num-1)) return false; // 判断是否为2的幂 if(num&0x55555555) return true; // 判断是否为4的幂 return false; } };
0x55555555 <-> 1010101010101010101010101010101
相关文章推荐
- LeetCode 第 342 题(Power of Four)
- LeetCode191 Number of 1 Bits. LeetCode231 Power of Two. LeetCode342 Power of Four
- 【LeetCode-342】 Power of Four(C++)
- LeetCode 第 342 题(Power of Four)
- Leetcode 342 Power of Four
- leetcode:bits:Power of Four(342)
- Leetcode Power of Four 342
- 位操作-leetcode 342 Power of Four
- leetcode 342 Power of four
- [leetcode-342]Power of Four(java)
- LeetCode 342 Power of Four
- LeetCode[342] Power of Four
- LeetCode之342,Power of Four
- LeetCode - 231/326/342 - Power of Two/Three/Four
- Python [Leetcode 342]Power of Four
- LeetCode 231,326,342 --Power of Two & Three & Four
- 【LeetCode-342】Power of Four
- Power of Four leetcode 342
- Leetcode 342 Power of Four
- Leetcode_342_Power of Four