Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1
Output: true
Explanation: 20 = 1
Example 2:
Input: 16
Output: true
Explanation: 24 = 16
Example 3:
Input: 218
Output: false
- Method 1:Bit operation
class Solution {
public boolean isPowerOfTwo(int n) {
if(n <= 0) return false;
int a = 1 << 31;
int count = 0;
for(int i = 0; i < 32; i++){
int cur = n & a;
if(cur != 0) count++;
a >>>= 1;
}
return count == 1;
}
}
- I just checked if a number can be fully divided by 2.
class Solution {
public boolean isPowerOfTwo(int n) {
if(n == 1) return true;
else if(n <= 0) return false;
while(n != 1){
if(n % 2 != 0) return false;
n /= 2;
}
return true;
}
}
- bit manipulation
class Solution {
public boolean isPowerOfTwo(int n) {
if(n <= 0) return false;
int temp = 0;
int count = 0;
for(int i = 0; i < 31; i++){
temp = n & 1;
if(temp == 1){
count ++;
if(count > 1) return false;
}
n >>= 1;
}
return true;
}
}