Description
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
.
Analysis
解法一:用(num & (num - 1)) == 0
來確定num是2的冪,由於4的冪中,1只可能位於奇數位(最低位設爲第0位),則有num & 0x55555555 == num
。
解法二:思路同上,但使用的反向思維,所有的偶數位應都爲0,即num & 0xAAAAAAAA == 0
。
解法三:判斷是否2的冪同上,但判斷是否爲4的冪時,借用了3,即(num - 1) % 3 == 0
。
Code
Version 1
class Solution {
public:
bool isPowerOfFour(int num) {
return (num > 0) && ((num & (num - 1)) == 0) && ((num & 0x55555555));
}
};
Version 2
class Solution {
public:
bool isPowerOfFour(int num) {
return (num > 0) && ((num & (num - 1)) == 0) && ((num & 0xAAAAAAAA) == 0);
}
};
Version 3
class Solution {
public:
bool isPowerOfFour(int num) {
return ((num & (num - 1)) == 0) && ((num - 1) % 3 == 0);
}
};
Appendix
- Link: https://leetcode.com/problems/power-of-four/
- Run Time:
- Version 1: 3ms
- Version 2: 6ms
- Version 3: 3ms
Question: don’t know why the 2nd solution is slower than others…