LeetCode之342,Power of Four
2017-02-04 11:37
441 查看
这个题和Power Of Two有很多相同点,可以在其基础上做适当延伸。
原题:
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?
特别注意上面那个:follow up的内容。
解决用的代码是:
class Solution {
public:
bool isPowerOfFour(int num) {
//if 2 or 8,return false
//if 4 or 16,return true
//so 0101 & 1000 =0000
//0101 & 0100 =0100
//get idea above,so
if(num<=0) return false;
return ((num&(num-1))==0 &&(num&0x55555555));
}
};
原题:
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?
特别注意上面那个:follow up的内容。
解决用的代码是:
class Solution {
public:
bool isPowerOfFour(int num) {
//if 2 or 8,return false
//if 4 or 16,return true
//so 0101 & 1000 =0000
//0101 & 0100 =0100
//get idea above,so
if(num<=0) return false;
return ((num&(num-1))==0 &&(num&0x55555555));
}
};
相关文章推荐
- LeetCode 第 342 题(Power of Four)
- LeetCode 342 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
- LeetCode191 Number of 1 Bits. LeetCode231 Power of Two. LeetCode342 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