Leetcode (372) Super Pow
2016-11-17 00:00
393 查看
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 = 2
b = [3]
Result: 8
Example2:
a = 2
b = [1,0]
Result: 1024
题意:给定一个小数a(int),和一个超大数b(用数组形式按位存),求abmod1337
思路:
快速幂取模的思路,将大数用高精度除以2即可,复杂度约为 O(nlogn)
递归思路ab0b1...bn=(ab0b1...bn−1)10∗abn,于是即可递归求解
不过就是不知道为什么C++写的快速幂对于同样的样例,run code为几十ms,提交就会TLE,感觉也没有什么undefined behavior= =。。有点无解。于是一怒之下就诞生了一行的python递归求解思路了。。。
C++ code
Python code
小碎碎念:这个递归版本其实可以进行尾递归优化(foldRight,或者说foldLeft实现的foldRight),但是Python好像没有尾递归优化,又不支持Scala= =那就不尝试了
Example1:
a = 2
b = [3]
Result: 8
Example2:
a = 2
b = [1,0]
Result: 1024
题意:给定一个小数a(int),和一个超大数b(用数组形式按位存),求abmod1337
思路:
快速幂取模的思路,将大数用高精度除以2即可,复杂度约为 O(nlogn)
递归思路ab0b1...bn=(ab0b1...bn−1)10∗abn,于是即可递归求解
不过就是不知道为什么C++写的快速幂对于同样的样例,run code为几十ms,提交就会TLE,感觉也没有什么undefined behavior= =。。有点无解。于是一怒之下就诞生了一行的python递归求解思路了。。。
C++ code
class Solution { private: inline bool isZero(const vector<int>& b) { for (int i=0;i<b.size();++i) { if (b[i]) return false; } return true; } inline bool half(vector<int>& b) { int last=0; for (int i=0;i<b.size();++i) { int x = last*10+b[i]; b[i] = x/2; last = x%2; } return last; } public: int superPow(long long aa, vector<int>& b) { if (b.empty()) return 1; int ans=1, a=aa%1337; while (!isZero(b)) { if (half(b)) { ans = (ans*a)%1337; } a = (a*a)%1337; } return ans; } };
Python code
class Solution(object): def superPow(self, a, b): """ :type a: int :type b: List[int] :rtype: int """ return pow(a, b[-1], 1337) * pow(self.superPow(a, b[:-1]), 10, 1337) % 1337 if b else 1
小碎碎念:这个递归版本其实可以进行尾递归优化(foldRight,或者说foldLeft实现的foldRight),但是Python好像没有尾递归优化,又不支持Scala= =那就不尝试了
相关文章推荐
- [java][leetcode 372]Super Pow
- LeetCode 372. Super Pow (快速幂取模)
- LeetCode 372 Super Pow
- LeetCode 第 372 题 (Super Pow)
- LeetCode 第 372 题 (Super Pow)
- [leetcode-372]Super Pow(java)
- LeetCode 372 Super Pow
- 372. Super Pow(LeetCode)
- Leetcode 372. Super Pow (Medium) (cpp)
- Math-372-Super Pow
- LeetCode Super Pow(快速求幂算法)
- LeetCode 372. Super Pow解题思路(超详细)
- leetcode_372. Super Pow
- [Leetcode] 372. Super Pow 解题报告
- leetcode:数学:spuer pow(372)
- LeetCode "Super Pow"
- LeetCode: Super Pow
- leetcode Super Pow
- LeetCode Super Pow详解
- Leetcode: Super Pow