[LeetCode] Power of Two

231. Power of Two

Given an integer n, return true if it is a power of two. Otherwise, return false.

An integer n is a power of two, if there exists an integer x such that n == 2x.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n < 0) return false;
while(n) {
if(n&1) {
if(n == 1) return true;
else return false;
}
n>>=1;
}
return false;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/21/PS/LeetCode/power-of-two/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.