幂专题

幂专题

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值