美文网首页
「算法」372. 超级次方

「算法」372. 超级次方

作者: MrLiuYS | 来源:发表于2021-12-05 10:23 被阅读0次

    <div class="image-package"><img src="https://img.haomeiwen.com/i1648392/6a130d84adc668bc.jpg" contenteditable="false" img-data="{"format":"jpeg","size":207264,"height":900,"width":1600}" class="uploaded-img" style="min-height:200px;min-width:200px;" width="auto" height="auto"/>
    </div><blockquote><p>你的任务是计算 ab 对 1337 取模,a 是一个正整数,b 是一个非常大的正整数且会以数组形式给出。

    示例 1:

    输入:a = 2, b = [3]
    输出:8
    示例 2:

    输入:a = 2, b = [1,0]
    输出:1024
    示例 3:

    输入:a = 1, b = [4,3,3,8,5,2]
    输出:1
    示例 4:

    输入:a = 2147483647, b = [2,0,0]
    输出:1198

    提示:

    1 <= a <= 231 - 1
    1 <= b.length <= 2000
    0 <= b[i] <= 9
    b 不含前导 0

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/super-pow
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。</p></blockquote><h1 id="nu9ff">题解</h1><div class="image-package"><img src="https://img.haomeiwen.com/i1648392/d54a224451c92389.jpg" contenteditable="false" img-data="{"format":"jpeg","size":67200,"height":832,"width":1304}" class="uploaded-img" style="min-height:200px;min-width:200px;" width="auto" height="auto"/>
    </div><h2 id="xai6y">Swift</h2><blockquote><p>class Solution {
    let mod = 1337

    func superPow(_ a: Int, _ b: [Int]) -> Int {
    var a = a
    var ans = 1

    for index in (0 ..< b.count).reversed() {
    ans = Int(ans * pow(a, b[index]) % mod)
    a = pow(a, 10)
    }

    return ans
    }

    func pow(_ x: Int, _ n: Int) -> Int {
    var x = x
    var n = n
    var res = 1
    while n != 0 {
    if n % 2 != 0 {
    res = (res * x % mod)
    }
    x = (x * x % mod)
    n /= 2
    }
    return res
    }
    }

    print(Solution().superPow(2147483647, [2, 0, 0]))
    </p></blockquote><p>
    </p><p>
    </p><p>
    </p>

    相关文章

      网友评论

          本文标题:「算法」372. 超级次方

          本文链接:https://www.haomeiwen.com/subject/kgeixrtx.html