Given an integer, write a function to determine if it is a power of two.
思路:注意题意是判断一个数是不是2的幂。一直除以2,如果除不尽就不是2的幂,当等于1的时候,就返回true;
代码如下(已通过leetcode)
public class Solution {
public boolean isPowerOfTwo(int n) {
if(n<1) return false;
while(n>0){
if(n==1) return true;
if(n%2==0) {
n=n/2;
} else return false;
}
return true;
}
}