Leetcode 231. Power of Two

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Power of Two

2. Solution

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n == 0) {
return false;
}
while(n != 1) {
if(n % 2) {
return false;
}
n /= 2;
}
return true;
}
};
  • Version 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n == 0) {
return false;
}
while(n != 1) {
if(n % 2) {
return false;
}
n >>= 1;
}
return true;
}
};
  • Version 3
1
2
3
4
5
6
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && !(n & (n - 1));
}
};

Reference

  1. https://leetcode.com/problems/power-of-two/description/
如果有收获,可以请我喝杯咖啡!