[CodeWars] Last digit of a large number

CodeWars里的5kyu题目Last digit of a leage number

题目说明:

Description:
Define a function that takes in two non-negative integers aaa and bbb and returns the last decimal digit of aba^ba
b
. Note that aaa and bbb may be very large!

For example, the last decimal digit of 979^79
7
is 999, since 97=47829699^7 = 47829699
7
=4782969. The last decimal digit of (2200)2300({2{200}}){2^{300}}(2
200
)
2
300

, which has over 109210^{92}10
92
decimal digits, is 666. Also, please take 000^00
0
to be 111.

You may assume that the input will always be valid.

Examples
last_digit(4, 1) # returns 4
last_digit(4, 2) # returns 6
last_digit(9, 7) # returns 9
last_digit(10, 10 ** 10) # returns 0
last_digit(2 ** 200, 2 ** 300) # returns 6
Remarks
JavaScript, C++, R, PureScript
Since these languages don’t have native arbitrarily large integers, your arguments are going to be strings representing non-negative integers instead.

Python解决办法:

为了避免时间超限,将0-9数字分为三组,分别是1、4、2次循环得到原先数字,将n1去10的余数,将n2去对应循环次数的余数,进行简化计算。

def last_digit(n1, n2):
    l1 = [0, 1, 5, 6]
    l2 = [2, 3, 7, 8]
    l3 = [4, 9]
    n1 = n1 % 10
    if n2 == 0:
        return 1
    if n1 in l1:
        return n1
    elif n1 in l2:
        n2 = n2 % 4
        if n2 == 0:
            m = (n1 ** 4) % 10
            return m
        else:
            m = (n1 ** n2) % 10
            return m
    elif n1 in l3:
        n2 = n2 %2
        if n2 ==0:
            m = (n1 ** 2) % 10
            return m
        else:
            m = (n1 ** n2) % 10
            return m
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值