LeetCode/solutions/372. Super Pow.md

49 lines
1.1 KiB
Markdown
Raw Normal View History

2019-12-13 09:16:05 +00:00
# [372. Super Pow](https://leetcode.com/problems/super-pow/)
# 思路
题目让实现一个超级pow函数最后结果对1337取模。
先不考虑对1337取模的话实现pow函数是很简单的就是一个二分的思想:
``` C++
int pow(int x, int y){ // x >=0, y >= 0
if(y == 0) return 1;
if(y == 1) return x;
return pow(x, y/2) * pow(x, y - y/2);
}
```
由于此题的结果可能很大需要对1337取模所以我们在计算的过程中能对1377取模的地方就对1337取模:
``` C++
int pow(int x, int y){ // (x^y) % 1337
if(y == 0) return 1;
x %= 1337;
if(y == 1) return x;
return pow(x, y/2) * pow(x, y - y / 2) % 1337;
}
```
剩下就好写了,见下面完整代码。
# C++
``` C++
class Solution {
private:
int pow(int x, int y){ // (x^y) % 1337
if(y == 0) return 1;
x %= 1337;
if(y == 1) return x;
return pow(x, y/2) * pow(x, y - y / 2) % 1337;
}
public:
int superPow(int a, vector<int>& b) {
int res = 1;
for(int i = 0; i < b.size(); i++)
res = pow(res, 10) * pow(a, b[i]) % 1337;
return res;
}
};
```