welcome to my blog
LeetCode Top Interview Questions 231. Power of Two (Java版; Easy)
题目描述
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
第一次做; 最优解, 利用性质:2的幂满足n&(n-1)==0, 还要注意n>0
class Solution {
public boolean isPowerOfTwo(int n) {
return n>0 && (n&(n-1))==0;
}
}
第一次做; 递归, base case: n==0, n==1; 其余的按照%2是否为零分成两个分支讨论
/* 除了2^0, 2的幂的因数只有2 特殊的例子:0, 1 */
class Solution {
public boolean isPowerOfTwo(int n) {
if(n<1)
return false;
if(n==1)
return true;
if(n%2==0){
return isPowerOfTwo(n/2);
}
return false;
}
}
第一次做; 让一个数每次乘2, 如果某一次能等于n, 说明n是2的幂, 如果大于n, 说明n不是2的幂, 注意避免溢出问题
class Solution {
public boolean isPowerOfTwo(int n) {
//找个数每次乘2, 如果结果大于n说明n不是2的幂
int a = 1;
//注意避免溢出问题
while(a<n && a<Integer.MAX_VALUE/2){
a = a*2;
}
return a==n;
}
}
还没有评论,来说两句吧...