Given an integer, write a function to determine if it is a power of two.
第一次嘗試代碼:
public class Solution {
public boolean isPowerOfTwo(int n) {
//如果爲0,則false
if(n==0){
return false;
}
//2^0=1
if(n==1){
return true;
}
//n爲奇數則肯定不是,若是偶數則遞歸解決
if(n%2!=0){
return false;
}
else{
Solution s = new Solution();
return s.isPowerOfTwo(n/2);
}
}
}
第二次嘗試代碼:
public class Solution {
public boolean isPowerOfTwo(int n) {
//負數與0都不是
if(n<=0){
return false;
}
//如果n與n-1與運算之後不爲0,則表明n的二進制數1的個數大於1,則判定肯定不是
else if((n&(n-1))!=0){
return false;
}
else{
return true;
}
}
}