• 258. Add Digits


    Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 

    For example:

    Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

    Follow up: Could you do it without any loop/recursion in O(1) runtime?

    树根问题,参考https://zh.wikipedia.org/wiki/%E6%95%B8%E6%A0%B9

    树根的用途:

    数根可以计算模运算同余,对于非常大的数字的情况下可以节省很多时间

    数字根可作为一种检验计算正确性的方法。例如,两数字的和的数根等于两数字分别的数根的和。

    另外,数根也可以用来判断数字的整除性,如果数根能被3或9整除,则原来的数也能被3或9整除。

    class Solution(object):
        def addDigits(self, num):
            """
            :type num: int
            :rtype: int
            """
            if num == 0: return 0
            else:
                return num - 9 * ((num - 1) / 9)

  • 相关阅读:
    1069.查找学生信息
    1023.Excel排序
    1061.成绩排序
    bzoj 1113
    bzoj 1112 treap树
    bzoj 1225 dfs + 一点点数论
    bzoj 1224
    UESTC
    HDU 3530 单调队列
    bzoj 1233
  • 原文地址:https://www.cnblogs.com/sxbjdl/p/5221476.html
Copyright © 2020-2023  润新知