Title description
Given an integer, write a function to determine whether it is a power of 2.
Example 1:
输入: 1
输出: true
解释: 20 = 1
示例 2:
输入: 16
输出: true
解释: 24 = 16
示例 3:
输入: 218
输出: false
Problem solving ideas
My idea is to count the number of 1s in the binary form of the input number. If the converted binary string has only 1 1, it is a power of 2, otherwise it is not
Code
bool isPowerOfTwo(int n){
int count=0;
while(n){
count+= n%2;
n/=2;
}return count==1?true:false;
}