[LintCode] 快速幂 Fast Power

98 篇文章 0 订阅

计算a^n % b,其中a,b和n都是32位的整数。

样例
例如 231 % 3 = 2
例如 1001000 % 1000 = 0

挑战
O(logn)

Calculate the a^n % b where a, b and n are all 32bit integers.

Example
For 231 % 3 = 2
For 1001000 % 1000 = 0

Challenge
O(logn)

不懂快速幂的小伙伴请看:http://blog.csdn.net/xuruoxin/article/details/8578992
思路:http://blog.csdn.net/y990041769/article/details/22311889

class Solution {
    /*
     * @param a, b, n: 32bit integers
     * @return: An integer
     */
    public static int fastPower(int a, int b, int n) {
        if(b == 0 || n < 0) return 0;
        if(b == 1 && n == 0) return 0;
        long result = 1l, atem = a;
        while(n > 0) {
            if((n & 1) == 1) {//n的最后一位为1
                result = (result * atem) % b;
            }
            atem = (atem % b) * (atem % b) % b;
            n >>= 1;
        }
        return (int)result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值