leetcode Super Pow
2016-07-24 20:46
351 查看
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:
Example2:
Credits:
Special thanks to @Stomach_ache for adding this problem and creating all test cases.
这题是真没想出来,看解法思路是这样的,首先需要了解一个数学理论:
(a*b)%c=(a%c)*(b%c),由于这道题会出现溢出情况,所以这个理论会经常使用。
再有就是求n次方的问题,递归根据奇偶数讨论即可:
an extremely large positive integer given in the form of an array.
Example1:
a = 2 b = [3] Result: 8
Example2:
a = 2 b = [1,0] Result: 1024
Credits:
Special thanks to @Stomach_ache for adding this problem and creating all test cases.
这题是真没想出来,看解法思路是这样的,首先需要了解一个数学理论:
(a*b)%c=(a%c)*(b%c),由于这道题会出现溢出情况,所以这个理论会经常使用。
再有就是求n次方的问题,递归根据奇偶数讨论即可:
public int superPow(int a, int[] b) { if(isZero(b)) return 1; a=a%1337; boolean isOdd=true; if(b[b.length-1]%2==0) isOdd=false; divide(b,2); int res=superPow(a,b); res=res%1337; res*=res; res=res%1337; if(isOdd){ res=(res*a)%1337; } return res; } public void divide(int[] b,int a){ int temp=0; for(int i=0;i<b.length;i++){ b[i]+=temp*10; temp=b[i]%a; b[i]/=a; } } public boolean isZero(int[] a){ for(int i=a.length-1;i>=0;i--){ if(a[i]!=0) return false; } return true; }
相关文章推荐
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- C#递归算法之分而治之策略
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- C#算法之大牛生小牛的问题高效解决方法
- C#算法函数:获取一个字符串中的最大长度的数字
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- 经典排序算法之冒泡排序(Bubble sort)代码
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法