forked from wangcy6/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path372.超级次方.cpp
64 lines (59 loc) · 1.23 KB
/
372.超级次方.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
* @lc app=leetcode.cn id=372 lang=cpp
*
* [372] 超级次方
*
* https://leetcode-cn.com/problems/super-pow/description/
*
* algorithms
* Medium (41.41%)
* Likes: 72
* Dislikes: 0
* Total Accepted: 5.4K
* Total Submissions: 12.8K
* Testcase Example: '2\n[3]'
*
* 你的任务是计算 a^b 对 1337 取模,a 是一个正整数,b 是一个非常大的正整数且会以数组形式给出。
*
* 示例 1:
*
* 输入: a = 2, b = [3]
* 输出: 8
*
*
* 示例 2:
*
* 输入: a = 2, b = [1,0]
* 输出: 1024
*
*/
// @lc code=start
class Solution
{
public:
/*
第一次思考:
首先你可以马上想到,求a^b,(1)计算B大小,(2)然后power
第二次思考:b 是一个非常大的正整数且会以数组形式给出. 需要拆分B大小
b=123=1*100+2*20+3*1
a^b=a^3*a^0
*/
int superPow(int a, vector<int> &b)
{
long long res = 1;
for (int i = 0; i < b.size(); ++i)
{
res = pow(res, 10) * pow(a, b[i]) % 1337;
}
return res;
}
int pow(int x, int n)
{
if (n == 0)
return 1;
if (n == 1)
return x % 1337;
return pow(x % 1337, n / 2) * pow(x % 1337, n - n / 2) % 1337;
}
};
// @lc code=end