372. Super Pow
来源:互联网 发布:漳州网络诈骗举报平台 编辑:程序博客网 时间:2024/06/04 20:13
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.
Example1:
a = 2b = [3]Result: 8
Example2:
a = 2b = [1,0]Result: 1024
Credits:
Special thanks to @Stomach_ache for adding this problem and creating all test cases.
这里b是以数组的形式提供,意味着可能很长。这里采用递归的形式,递归条件是:
return (powMod(sPow(a, b, length - 1, k), 10, k) * powMod(a, b[length - 1], k)) % k;
代码如下:
public class Solution { public int superPow(int a, int[] b) { return sPow(a, b, b.length, 1337); } private int sPow(int a, int[] b, int length, int k) { if (length == 1) { return powMod(a, b[0], k); } return (powMod(sPow(a, b, length - 1, k), 10, k) * powMod(a, b[length - 1], k)) % k; } private int powMod(int a, int n, int k) { a = a % k; int result = 1; for (int i = 0; i < n; i ++) { result = (result * a) % k; //这里每算一步都%k对最后结果没有影响,还能防止a*a....*a*a溢出,比如9^10就会溢出。 } return result; }}
0 0
- leetcode.372. Super Pow
- LeetCode 372. Super Pow
- 372. Super Pow
- 372. Super Pow
- [LEETCODE] 372. super pow
- LeetCode--372. Super Pow
- 372. Super Pow
- leetcode 372. Super Pow
- Leetcode 372. Super Pow
- [leetcode] 372. Super Pow
- Leetcode: 372.Super Pow
- 372. Super Pow
- 372. Super Pow(LeetCode)
- 372. Super Pow
- LeetCode 372. Super Pow
- 372. Super Pow
- [LeetCode]372. Super Pow
- 372. Super Pow
- Unity3D说明文档翻译-GameObject
- 基于Java语言的安卓编程之ListView(下)
- 数据挖掘读书笔记-分类-决策树
- Project Euler Problem 25 1000-digit Fibonacci number
- L2-012 关于堆的判断
- 372. Super Pow
- 数据库索引
- Java HashMap的死循环
- 数据链路层
- web前端编程规范
- Maven入门指南① :Maven 快速入门及简单使用
- Docker版本升级至17.03
- Unity3D说明文档翻译-Introduction to Components
- 357. Count Numbers with Unique Digits