您的位置:首页 > 其它

LeetCode - 231/326/342 - Power of Two/Three/Four

2017-07-18 09:52 417 查看
231. Power of Two

Given an integer, write a function to determine if it is a power of two.

判断一个数是不是2的幂。我写的是不断地除以2除以2除以2,很一般的思路。

看评论区有一个很巧的做法,感觉超优雅!是2的幂就表明这个数的二进制只能有一个1,那样(n & (n - 1))就应该为0。凡是不为0的,肯定不是2的幂。

时间复杂度O(1),空间复杂度0

class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && !(n & (n-1));
}
};


326. Power of Three

Given an integer, write a function to determine if it is a power of three.

Follow up:

Could you do it without using any loop / recursion?
想了很久很久以后,分析了一波二进制以后。。。还是只会写循环。。。(为什么我会去分析二进制,那是2进制又不是3进制【扶额】)
看到评论区的做法后,感觉自己。。。

3^20 > INT_MAX,我们取3^19,只要是3的幂,就一定能被3^19取余为0。(本来还想这样会不会有错,发现他所有的因子都是3的幂,唔,那就肯定没错了)

class Solution {
public:
bool isPowerOfThree(int n) {
return n > 0 && (1162261467 % n == 0);
}
};


342. 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?
是否是4的幂。
是4的幂就一定是2的幂,然后再排除是2的幂就可以了

评论区高票答案排除的方法是(num & 0x55555555) != 0。(就是8个0101,刚好32位)

class Solution {
public:
bool isPowerOfFour(int num) {
return num > 0 && !(num & (num-1)) && ((num - 1) % 3 == 0);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: