题目
Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1 Output: true Explanation: 20 = 1
Example 2:
Input: 16 Output: true Explanation: 24 = 16
Example 3:
Input: 218 Output: false
十分钟尝试
递归,思路正确,后来基准条件稍微有问题,不知道如何区分,n=1,还是递归调用的时候中间值的1.比如输入是3,如果if判断n==1返回true,那么3第二次invoke就是1,返回true。这个是不正确的。判断对n求mod,等于0才递归调用。这样可以解决。代码如下:
class Solution {
public boolean isPowerOfTwo(int n) {
if(n==0) return false;
if(n==1) return true;
if(n%2==0){
return isPowerOfTwo(n/2);
}
return false;
}
}