leetcode231. 2 的幂
用很丑陋的递归做出来的
class Solution {
public boolean isPowerOfTwo(int n) {
if (n == 1) {
return true;
}
if (n <= 0) {
return false;
}
if(n % 2 != 0) {
return false;
}
return getAns(n);
}
public static boolean getAns(int n) {
if (n == 1) {
return true;
}
if (n % 2 == 1) {
return false;
}
if (n == 0) {
return true;
}
return getAns(n/2);
}
}
看了一下题解,发现完全可以简化成这样。。。
class Solution {
public boolean isPowerOfTwo(int n) {
if (n == 1) {
return true;
}
if (n <= 0) {
return false;
}
if(n % 2 != 0) {
return false;
}
return isPowerOfTwo(n/2);
}
}
更牛逼的做法
class Solution {
public boolean isPowerOfTwo(int n) {
for (int i = 0; i < 31; i++) {
if (n == 1 << i) {
return true;
}
}
return false;
}
}