# Leetcode NO.231 Power of Two

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

power of 2的数看十进制，没有什么特别的地方，但是转换成二进制之后，都是100000的形式，最高位是1，其余位都是0，然后，这个数减1，就变为011111，最高位（已消失）为0，之后都是1，所以这两个数按位与(&)则变为0000000000.。。根据这个特性，可以解决这道题，代码如下:

class Solution {
public:
bool isPowerOfTwo(int n) {
if (n <= 0) {
return false;
}
return !(n & (n-1));
}
};

public:
bool isPowerOfTwo(int n) {
if (n <= 0) {
return false;
}
while ((n >> 1) << 1 == n) {
n >>= 1;
}
return (n == 1) ? true: false;
}
};

#### LeetCode No.231 Power of Two

2016-11-11 19:18:46

#### leetcode 231: Power of Two

2015-07-07 05:01:24

#### LeetCode 231: Power of Two

2015-07-06 18:34:20

#### [LeetCode] Power of Three | Power of Two

2016-01-28 21:39:28

#### [LeetCode] 231. Power of Two

2017-07-05 10:11:42

#### Leetcode - Power of Two

2016-05-05 10:12:27

#### 【LeetCode】Power of Two

2015-07-06 13:38:38

#### [leetcode] Power of two

2015-08-12 14:53:33

#### [leetCode] Power of Two

2015-07-06 23:22:59

#### 【Leetcode Algorithm】Power of Two

2015-07-06 21:45:38