231. Power of Two
Given an integer, write a function to determine if it is a power of two.
解法一
public class Solution {
public boolean isPowerOfTwo(int n) {
if (n <= 0) return false;
return (n & (n - 1)) == 0;
}
}
解法二
public class Solution {
public boolean isPowerOfTwo(int n) {
return n>0 && Integer.bitCount(n) == 1;
}
}
解法三
public class Solution {
public boolean isPowerOfTwo(int n) {
return n>0 && (n==1 || (n%2==0 && isPowerOfTwo(n/2)));
}
}
本文介绍三种不同的方法来判断一个整数是否为2的幂次。方法包括位运算检查、二进制位计数以及递归除以2的方式。这些方法简单高效,适用于多种编程场景。
692

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



