Given an integer, write a function to determine if it is a power of two.
意:推斷一個數是不是2的n次冪算法
假設一個數小於或等於0。必定不是2的冪次數
假設一個大於0且數是2的n次冪,則其的二進制形式有且僅有一個1,反之成立。markdown
public class Solution {
public boolean isPowerOfTwo(int n) {
if(n<=0)
return false;
int i = 0;
int countBit = 0;
while(i < 32){
if((n&(1<<i))!=0)
countBit++;
i++;
}
if(countBit != 1)
return false;
return true;
}
}
T(n)=O(1)spa
public static void main(String [] args){
int n = 4;
Solution s = new Solution();
System.out.println(s.isPowerOfTwo(n));
}
truecode