码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Power of Four 判断4的次方数

时间:2016-04-18 13:29:50      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:

 

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.

 

这道题让我们判断一个数是否为4的次方数,那么最直接的方法就是不停的除以4,看最终结果是否为1,参见代码如下:

 

解法一:

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

 

还有一种方法是跟Power of Three中的解法三一样,使用换底公式来做,讲解请参见之前那篇博客:

 

解法二:

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

 

下面这种方法是网上比较流行的一种解法,思路很巧妙,首先根据Power of Two中的解法二,我们知道num & (num - 1)可以用来判断一个数是否为2的次方数,更进一步说,就是二进制表示下,只有最高位是1,那么由于是2的次方数,不一定是4的次方数,比如8,所以我们还要其他的限定条件,我们仔细观察可以发现,4的次方数的最高位的1都是计数位,那么我们只需与上一个数(0x55555555) <==> 1010101010101010101010101010101,如果得到的数还是其本身,则可以肯定其为4的次方数:

 

解法三:

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

 

类似题目:

Power of Three

Power of Two

 

参考资料:

https://leetcode.com/discuss/97944/c-solution-using-bit-manipulation-with-one-line-code

 

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Power of Four 判断4的次方数

标签:

原文地址:http://www.cnblogs.com/grandyang/p/5403783.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!