• 边工作边刷题:70天一遍leetcode: day 59


    Add Digits

    要点:暴力解肯定是不行的。这题就是一道小学数学题:num = (a + b + c + d + e) + (a * 9999 + b * 999 + c * 99 + d * 9),所以两边%9是一样的。这样右边重复这个公式(可以利用(x + y) % z = (x % z + y % z) % z,和 x % z % z = x % z)。最终得到1位数k%9num%9。这个num%9和实际的k还有一点差异:如果k9,那么%9=0,所以要特殊处理,其他情况都一样。

    class Solution(object):
        def addDigits(self, num):
            """
            :type num: int
            :rtype: int
            """
            if num!=0 and num%9==0:
                return 9
            return num%9
    
    
  • 相关阅读:
    Beta 冲刺(1/7)
    福大软工 · 第十次作业
    11111111
    101
    7
    6
    5
    4
    p
    b2
  • 原文地址:https://www.cnblogs.com/absolute/p/5690328.html
Copyright © 2020-2023  润新知