[leetcode] 231.Power of Two

来源:互联网 发布:部落冲突弓箭升级数据 编辑:程序博客网 时间:2024/05/19 21:16

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

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
题意:
判断一个数是否是2的指数倍。
思路:
考虑特殊情况n<=0,不是2的指数倍,1是的。
采用递归的方法,如果n%2!=0说明不是指数。否则递归查看n/2是不是。
以上。
代码如下:

class Solution {public:    bool isPowerOfTwo(int n) {        if(n == 0)return false;        else if(n == 1)return true;        else if(n % 2 != 0)return false;        else return isPowerOfTwo(n/2);    }};

当然,这是最简单的思路,另外我们可以考虑一个数字组成,如果该数字大于0,并且是2的指数倍的话,那么这个数字可以表示成这样的二进制数,00000…00100…000,只有第k位上是1,其余位都是0。那么这个数字减去1之后,1到k-1位上是1,其余位是1,即00000..00011…111,所以观察可得n&(n-1) 等于0。
以上。
代码如下:
class Solution {
public:
bool isPowerOfTwo(int n) {
return (n > 0) && (n&(n-1)) == 0;
}
};

0 0
原创粉丝点击