mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 372. Super Pow.md
This commit is contained in:
parent
f093f95027
commit
cc826986be
48
solutions/372. Super Pow.md
Normal file
48
solutions/372. Super Pow.md
Normal file
@ -0,0 +1,48 @@
|
||||
# [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;
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in New Issue
Block a user