您的位置:首页 > 其它

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

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= =那就不尝试了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode