题目: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)));
}
}
本文介绍了一种算法来确定一个整数是否为2的幂次。提供了四种不同的实现方法,包括迭代和递归的方式,并通过具体的Java代码实现了这些算法。
333

被折叠的 条评论
为什么被折叠?



