mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
559 B
559 B
231. Power of Two
思路
求n是否是2的幂。
- 首先若n不是正数肯定直接返回false,若n为1直接返回true;
- 若n是不为1的奇数返回false;
- 令n = n / 2,若n=1则返回true否则返回第2步。
C++
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n <= 0) return false;
if(n == 1) return true;
while(n > 1){
if(n % 2 == 1) return false;
n /= 2;
}
return true;
}
};