class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && (n & (n-1))==0;
}
};
n&n-1==0 时 n为2的倍数
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && (n & -n) == n;
}
};
n & -n == n 也行n为2的倍数
class Solution {
public:
bool isPowerOfThree(int n) {
while(n&&n%3==0){
n/=3;
}
return n==1;
}
};
class Solution {
public:
bool isPowerOfThree(int n) {
if(n <= 0) {
return false;
}
int x = (int)(log2(n) / log2(3) + 1e-8);
return fabs(n - pow(3, x)) < 1e-8;
}
};
求1+2+....+n
class Solution {
public:
int res;
int sumNums(int n) {
bool x = n > 1 && sumNums(n - 1) > 0;
res += n;
return res;
}
};
这篇博客探讨了如何使用位操作判断一个整数是否为2的幂次方,通过n&(n-1)等于0或者n&(n-1)不等于0来检查。此外,还展示了判断一个数是否为3的幂次方的方法,以及利用对数运算判断是否为3的幂次方。最后,提到了一个计算1到n之和的递归算法。
2万+

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



