您的位置:首页 > 其它

<LeetCode OJ> 342. Power of Four

2016-04-21 20:52 483 查看
Total Accepted: 4769 Total
Submissions: 14338 Difficulty: Easy

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?
Credits:

Special thanks to @yukuairoy for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Hide Tags
Bit Manipulation

Show Similar Problems

分析:

老题目了!分析略。

方法1:

反复相除。时间复杂度o(lg(n))

class Solution {
public:
bool isPowerOfFour(int num) {
while(num>0 && num%4==0)
num/=4;
return num==1;
}
};


方法2:

log函数取对数

class Solution {
public:
bool isPowerOfFour(int num) {
double res = log10(num) / log10(4);  //有精度问题,不要用以指数2.718为低的log函数
return (res - int(res) == 0) ? true : false;
}
};


方法3:

位运算,没有方法1快呢!

class Solution {
public:
bool isPowerOfFour(int num) {
if (num <= 0)
return false;
//(num & (num-1)) == 0这个条件有可能是2的幂产生的。
//(num & 0x55555555) != 0这个条件为的是铲除2的幂
if ( (num & (num-1)) == 0 && (num & 0x55555555) != 0 )
return true;

return false;
}
};


注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/51212846

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:/article/3664871.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: