Leetcode (372) Super Pow

Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.

Example1:

a = 2
b = [3]

Result: 8
Example2:

a = 2
b = [1,0]

Result: 1024

  • 题意:给定一个小数a(int),和一个超大数b(用数组形式按位存),求 abmod1337
  • 思路:

    1. 快速幂取模的思路,将大数用高精度除以2即可,复杂度约为 O(nlogn)
    2. 递归思路 ab0b1...bn=(ab0b1...bn1)10abn ,于是即可递归求解
  • 不过就是不知道为什么C++写的快速幂对于同样的样例,run code为几十ms,提交就会TLE,感觉也没有什么undefined behavior= =。。有点无解。于是一怒之下就诞生了一行的python递归求解思路了。。。

  • C++ code

class Solution {
private:
    inline bool isZero(const vector<int>& b)
    {
        for (int i=0;i<b.size();++i)
        {
            if (b[i]) return false;
        }
        return true;
    }

    inline bool half(vector<int>& b)
    {
        int last=0;
        for (int i=0;i<b.size();++i)
        {
            int x = last*10+b[i];
            b[i] =  x/2;
            last =  x%2;
        }
        return last;
    }
public:
    int superPow(long long aa, vector<int>& b) {

        if (b.empty()) return 1;
        int ans=1, a=aa%1337;
        while (!isZero(b))
        {
            if (half(b))
            {
                ans = (ans*a)%1337; 
            }
            a = (a*a)%1337;
        }
        return ans;
    }
};
  • Python code
class Solution(object):
    def superPow(self, a, b):
        """
        :type a: int
        :type b: List[int]
        :rtype: int
        """
        return pow(a, b[-1], 1337) * pow(self.superPow(a, b[:-1]), 10, 1337) % 1337 if b else 1
  • 小碎碎念:这个递归版本其实可以进行尾递归优化(foldRight,或者说foldLeft实现的foldRight),但是Python好像没有尾递归优化,又不支持Scala= =那就不尝试了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值