LeetCode/solutions/231. Power of Two.md
2019-09-13 23:08:41 +08:00

22 lines
563 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [231. Power of Two](https://leetcode.com/problems/power-of-two/description/)
# 思路
求n是否是2的幂。
1. 首先若n不是正数肯定直接返回false若n为1直接返回true
2. 若n是不为1的奇数返回false
3. 令n = n / 2若n=1则返回true否则返回第2步。
# C++
``` 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;
}
};
```