★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-vcwelzzp-eg.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Your task is to calculate ab mod 1337 where a is a positive integer and bis an extremely large positive integer given in the form of an array.git
Example 1:github
Input: a = 2, b = [3] Output: 8
Example 2:數組
Input: a = 2, b = [1,0] Output: 1024
你的任務是計算 ab 對 1337 取模,a 是一個正整數,b 是一個很是大的正整數且會以數組形式給出。微信
示例 1:spa
輸入: a = 2, b = [3] 輸出: 8
示例 2:code
輸入: a = 2, b = [1,0] 輸出: 1024
68ms
1 class Solution { 2 let mod = 1337 3 func superPow(_ a: Int, _ b: [Int]) -> Int { 4 guard b.count > 0 else { 5 return 1 6 } 7 var num = 1 8 var tmpA = a 9 for tmpNum in b.reversed() { 10 num = powMod(tmpA, tmpNum) * num % mod 11 tmpA = powMod(tmpA, 10); 12 } 13 return num 14 } 15 16 private func powMod(_ a: Int, _ m: Int) -> Int{ 17 let tmpA = a % mod 18 var result = 1 19 for _ in 0 ..< m { 20 result = result * tmpA % mod 21 } 22 return result 23 } 24 }
76msorm
1 class Solution { 2 func superPow(_ a: Int, _ b: [Int]) -> Int { 3 var rst: Int = 1; 4 var x = a; 5 for n in b { 6 rst = newPow(rst, 10) * newPow(x, n) % 1337; 7 } 8 return rst; 9 } 10 11 func newPow(_ x: Int, _ n: Int) -> Int { 12 if n == 0{ 13 return 1; 14 } 15 if n == 1{ 16 return x % 1337; 17 } 18 19 return newPow(x % 1337, n / 2) * newPow(x % 1337, n - n / 2) % 1337; 20 } 21 }
108mshtm
1 class Solution { 2 func superPow(_ a: Int, _ b: [Int]) -> Int { 3 4 var result:Int=1 5 6 for i in 0...b.count-1 { 7 result = self.pow(result, 10) * pow(a, b[i]) % 1337 8 } 9 10 return result; 11 } 12 func pow(_ x: Int ,_ n: Int) -> Int { 13 if (n == 0) {return 1} 14 if (n == 1) {return x % 1337} 15 return pow(x % 1337, n / 2) * pow(x % 1337, n - n / 2) % 1337; 16 17 } 18 }
168msblog
1 class Solution { 2 func superPow(_ a: Int, _ b: [Int]) -> Int { 3 var res:Int = 1 4 for i in 0..<b.count 5 { 6 res = pow(res, 10) * pow(a, b[i]) % 1337 7 } 8 return res 9 } 10 11 func pow(_ x:Int,_ n:Int) -> Int 12 { 13 if n == 0 {return 1} 14 if n == 1 {return x % 1337} 15 return pow(x % 1337, n / 2) * pow(x % 1337, n - n / 2) % 1337 16 } 17 }