372. Super Pow

问题:

求a^b%base的值。

a为int型数

b为int数组,例如[1,2,3,4]代表:b=1234

base=1337。

Example 1:
Input: a = 2, b = [3]
Output: 8

Example 2:
Input: a = 2, b = [1,0]
Output: 1024

Example 3:
Input: a = 1, b = [4,3,3,8,5,2]
Output: 1

Example 4:
Input: a = 2147483647, b = [2,0,0]
Output: 1198

Constraints:
1 <= a <= 2^31 - 1
1 <= b.length <= 2000
0 <= b[i] <= 9
b doesn't contain leading zeros.

  

解法:math,DFS,Backtracking

参考:labubadong

首先,基本DFS规律为:

 

  • part1=a^4
  • part2=(a^[1,5,6]) ^10

构建自己的pow方法:mypow

能够计算 a^b

  • part1=mypow(a,4)
  • part2=mypow(backtrack(a,[1,5,6]),10)

最后结果res=( part1*part2 )%base

 

构建mypow方法:

为了快速计算,我们分奇偶数进行:

 

 

 mypow(a,b)=

  • a*mypow(a,b-1), b%2!=0
  • mypow(a,b/2)*mypow(a,b/2), b%2==0

 

代码参考:

 1 class Solution {
 2 public:
 3     int base = 1337;
 4     //c=a*b
 5     //c%k=(a%k)*(b%k)%k
 6     int myPow(int a, int b) {
 7         if(b==0) return 1;
 8         a = a%base;
 9         if(b%2) {//odd
10             return (a * myPow(a,b-1)) % base; 
11         } else {//even
12             int part = myPow(a,b/2);
13             return (part*part) % base;
14         }
15     }
16     int superPow(int a, vector<int>& b) {
17         if(b.empty()) return 1;
18         int cur = b.back();
19         int part1 = myPow(a, cur);
20         int part2 = 1;
21         b.pop_back();
22         if(!b.empty()) part2=myPow(superPow(a,b), 10);
23         return (part1*part2)%base;
24     }
25 };

 

posted @ 2021-04-01 10:16  habibah_chang  阅读(68)  评论(0编辑  收藏  举报