[leetcode] 372. Super Pow

441 篇文章 0 订阅
284 篇文章 0 订阅

Description

Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.

Example 1:

Input:

a = 2, b = [3]

Output:

8

Example 2:

Input:

a = 2, b = [1,0]

Output:

1024

分析

题目的意思是:求a的b次方。

  • 二分法,计算结果要对1337取余。由于给定的指数b是一个一维数组的表示方法,二分法处理起来肯定十分不方便,所以采用按位来处理。
  • 比如2 的23次方 = (2的2次方)的10次方 * 2的3次方, 所以我们可以从b的最高位开始,算出个结果存入res,然后到下一位是,res的十次方再乘以a的该位次方再对1337取余

代码

class Solution {
public:
    int superPow(int a, vector<int>& b) {
        long long res=1;
        for(int i=0;i<b.size();i++){
            res=pow(res,10)*pow(a,b[i])%1337;
        }
        return res;
    }
    int pow(int x,int n){
        if(n==0) return 1;
        if(n==1) return x%1337;
        return pow(x%1337,n/2)*pow(x%1337,n-n/2)%1337;
    }
};

参考文献

[LeetCode] Super Pow 超级次方

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值