题目:Power of Two
Given an integer, write a function to determine if it is a power of two.
One:以n为参数 n/2为变化率进行循环Iterable
public class Solution {
public boolean isPowerOfTwo(int n) {
if(n==1)return true;
while(n!=0){
if(n==1)return true;
if(n%2!=0)break;
n/=2;
}
return false;
}
}
Two:进一步简化
public class Solution {
public boolean isPowerOfTwo(int n) {
if(n==1)return true;
while(n%2==0){
n/=2;
}
return n==1;
}
}
Three:递归的方法Recursive
public class Solution {
public boolean isPowerOfTwo(int n) {
if(n==1)return true;
if(n<1||n%2 !=0)return false;
return isPowerOfTwo(n/2);
}
}
Four:Recursive进一步简化
public class Solution {
public boolean isPowerOfTwo(int n) {
return n>0 && (n==1 || (n%2==0 && isPowerOfTwo(n/2)));
}
}