372. 超级次方

题目

你的任务是计算 ab 对 1337 取模,a 是一个正整数,b 是一个非常大的正整数且会以数组形式给出。

示例 1:

输入:a = 2, b = [3]
输出:8
示例 2:

输入:a = 2, b = [1,0]
输出:1024
示例 3:

输入:a = 1, b = [4,3,3,8,5,2]
输出:1
示例 4:

输入:a = 2147483647, b = [2,0,0]
输出:1198

提示:

1 <= a <= 231 - 1
1 <= b.length <= 2000
0 <= b[i] <= 9
b 不含前导 0
daku

题解

😭😭,官方题解看不明白,不清楚为啥这个样写

class Solution {
    static final int MOD = 1337;

    public int superPow(int a, int[] b) {
        int ans = 1;
        for (int i = b.length - 1; i >= 0; --i) {
            ans = (int) ((long) ans * pow(a, b[i]) % MOD);
            a = pow(a, 10);
        }
        return ans;
    }

    public int pow(int x, int n) {
        int res = 1;
        while (n != 0) {
            if (n % 2 != 0) {
                res = (int) ((long) res * x % MOD);
            }
            x = (int) ((long) x * x % MOD);
            n /= 2;
        }
        return res;
    }
}

作者:力扣官方题解
链接:https://leetcode.cn/problems/super-pow/solutions/1138551/chao-ji-ci-fang-by-leetcode-solution-ow8j/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

自己用了BigInteger来写的,为了应对较大的数值,运行时间比较慢,不过勉强通过了力扣

 public int superPow2(int a, int[] b) {
        // 定义模数
        int MOD = 1337;
        // 对a转成BigInteger再取模处理
        BigInteger base = BigInteger.valueOf(a).mod(BigInteger.valueOf(MOD));
        // 把数组转成BigInteger
        BigInteger exponent = convertArrayToBigInteger(b);
        // 使用BigInteger的modPow方法,得到次方数并取模
        BigInteger result = base.modPow(exponent, BigInteger.valueOf(MOD));
        return result.intValue();
    }

    public BigInteger convertArrayToBigInteger(int[] arr) {
        StringBuilder sb = new StringBuilder();
        for (int num : arr) {
            sb.append(num);
        }
        return new BigInteger(sb.toString());
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

偷偷不学习

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

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

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

打赏作者

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

抵扣说明:

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

余额充值