幂专题
1、判断是否为2的幂
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<=0) return false;
return (n&(n-1)) == 0;
}
};
2、判断是否为4的幂
方法1 与0x55555555(奇数位全为1) 与
class Solution {
public:
bool isPowerOfFour(int num) {
if (num <= 0){
return false;
}
return (num & (num-1)) == 0 && ((num & 0x55555555 )== num);
}
};
方法2 :4^n =(3+1)^n 除3余1
class Solution {
public:
bool isPowerOfFour(int num) {
if (num <= 0){
return false;
}
return (num & (num-1)) == 0 && (num %3 ==1);
}
};
3、判断是否为3的幂
方法1:log函数 double 判断
class Solution {
public:
bool isPowerOfThree(int n) {
if(n<=0){
return false;
}
double res = log10(n) / log10(3);
return res - (int)res == 0?true:false;
}
};
方法2:转为3进制,1后面都为0
4、快速幂
int pow_fast(int a, int b) {
int ret = 1;
int base = a;
while (b) {
if (b & 1) { // 当前b最低位为1, 比如 1101最右边的1
ret *= base;
}
b >>= 1;
base *= base;
}
return ret;
}
5、快速幂的模
a^b%c ==( (a%c)^b)%c
// 快速幂取模 模板代码
int pow_fast_tpl(int a, int b, int c) {
int ret = 1;
int base = a % c;
while (b) {
if (b & 1) {
ret = (ret * base) % c;
}
base = (base * base) % c;
b >>= 1;
}
return ret;
}