您的位置:首页 > 其它

LeetCode 342. Power of Four

2016-05-20 19:19 459 查看
https://leetcode.com/problems/power-of-four/

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?

数学题+位运算。

因为是signed 32 bits,所以先保证num > 0。

然后2的幂的特征(num & (num - 1)) == 0,e.g. 0x1000 & 0x0111。

再对2的幂中筛选不是4的幂的。4的幂的二进制中1总是出现在奇数位,e.g. 4^1(0x0100), 4^2(0x00010000), 4^3(0x01000000),其他则是在偶数位,e.g. 2^1(0x0010), 2^3(0x1000), 2^5(0x00100000)。所以(num & 0x55555555) != 0,这里0x55555555正是signed 32 bits integer。

之前没注意位运算运算符&优先级低于==,需要加上括号。

C语言运算符_百度百科
http://baike.baidu.com/link?url=7D3QzeLlfI9pELy4OqJyyGE-WwRZhZ_mCI8ZSI6YdQHrldIIly3WnCTGnjzbypatAAodGjGFTUrTGJxkIbWFBq#2
还有一种解法(4^n - 1)都可以被3整除,所以可以判断(num > 0) && ((num & (num - 1)) == 0) && ((num - 1) % 3 == 0)

https://helloacm.com/how-to-check-if-integer-is-power-of-four-cc/

#include <iostream>
using namespace std;

class Solution {
public:
bool isPowerOfFour(int num) {
return ((num > 0) && ((num & (num - 1)) == 0) && ((num & 0x55555555) != 0));
}
};

int main ()
{
Solution testSolution;
bool result;

result = testSolution.isPowerOfFour(16);
cout << result << endl;

char ch;
cin >> ch;

return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: