【每日一题0807】末尾数字

:woman_mage:已知2个非负整数ab,请编写一个python函数,返回 ab 的末尾数字。注意,ab的数字可能非常巨大。

示例:97 应当返回9,因为97=4782969,末尾数字是9

题目难度:中等
题目来源:codewars

def last_digit(a:int, b:int):
    pass

assert last_digit(4, 1) == 4
assert last_digit(4, 2) == 6
assert last_digit(10, 100000) == 0
assert last_digit(2 ** 200, 2 ** 300) == 6
def last_digit(a: int, b: int):
    res = []
    for x in range(1, 10):
        last_int = int(str(a ** x)[-1])
        if last_int not in res:
            res.append(last_int)
        else:
            break
    return res[b % len(res) - 1]


assert last_digit(4, 1) == 4
assert last_digit(4, 2) == 6
assert last_digit(10, 100000) == 0
assert last_digit(2 ** 200, 2 ** 300) == 6
def last_digit(a: int, b: int):
    res = {0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: []}
    for i in range(0, 10):
        for j in range(1, 5):
            res[i].append(i ** j)

    for k, v in res.items():
        if a % 10 == k:
            return (res[k][b % 4 - 1]) % 10


assert last_digit(4, 1) == 4
assert last_digit(4, 2) == 6
assert last_digit(10, 100000) == 0
assert last_digit(2 ** 200, 2 ** 300) == 6

找规律,填数字

def last_digit(a:int,b:int):
    if a==0:
        return 0
    elif a>0 and b==0:
        return 1
    elif a>0 and b>0 and b<=4:
        res=int(str(a**b)[-1])
        return res
    else:
        list_a=[]
        for i in range(4):
            list_a.append(int(str(a**i)[-1]))
        if b%4==0:
            return list_a[-1]
        else:
            return list_a[b%4-1]

def last_digit(a: int,b: int):
n = b%4
if n==0:
return str(a)[-1]
else:
return str(int(str(a)[-1])**n)[-1]

参考思路:

  • 依次列出0~9每个数字的1~9次幂的结果
  • 分析末尾数字的规律:幂为5和幂为1时的尾数相等
  • 将幂数模4就得到了简化的幂数了
  • 计算简化后的结果,取尾数即可。
def last_digit(a:int, b:int):
    a_last = str(a)[-1:]
    
    if a_last == '0':
        return 0
    if b == 0:
        return 1
    if a_last in ('1', '5', '6'):
        return int(a_last)
    
    result = str(int(a_last) ** (b % 4))[-1:] if (b % 4) != 0 else str(int(a_last) ** 4)[-1:]
    return int(result)
    

assert last_digit(4, 1) == 4
assert last_digit(4, 2) == 6
assert last_digit(10, 100000) == 0
assert last_digit(2 ** 200, 2 ** 300) == 6
assert last_digit(0, 200) == 0

:partying_face: :partying_face: :partying_face: :partying_face: :partying_face: :partying_face:

1 Like

参考题解1:pow大法

def last_digit(a:int, b:int):
    return pow( a, b, 10 )

解题思路:使用内置函数,一步到位。

参考题解2:找规律

rules = {
    0: [0,0,0,0],   
    1: [1,1,1,1],
    2: [2,4,8,6],
    3: [3,9,7,1],
    4: [4,6,4,6], 
    5: [5,5,5,5], 
    6: [6,6,6,6], 
    7: [7,9,3,1], 
    8: [8,4,2,6], 
    9: [9,1,9,1],
}

def last_digit(a:int, b:int):
    ruler = rules[int(str(a)[-1])]
    return 1 if b == 0 else ruler[(b % 4) - 1]
1 Like

参考题解3:模4

def last_digit(a:int, b:int):
    return (a % 10) ** (b % 4 + 4 * bool(b)) % 10
1 Like
关闭