题目:给一个非负整数 num,反复添加所有的数字,直到结果只有一个数字。
例如:设定 num = 38,过程就像: 3 + 8 = 11, 1 + 1 = 2。 由于 2 只有1个数字,所以返回它。
进阶:你可以不用任何的循环或者递归算法,在 O(1) 的时间内解决这个问题么?
思路:嵌套两次循环即可
代码:

#!/usr/bin/env python
# encoding:utf-8
"""
__author__:adam
功能:非负整数各位相加
第一种方法
"""

class Solution(object):
    def addDigits(self,num):
        """
        :type num:str
        :type :int
        """
       sum_one = 0
        num_one = 0
        while(1):
            while(num):
                num_one = num % 10
                sum_one += num_one
                num /= 10
            if(sum_one < 10):
                break
            num = sum_one
            sum_one = 0
        return sum_one

if __name__ == "__main__":
m = Solution()
m.addDigits(1784)

方法二:借鉴他人经验,假设输入一个四位数num,各位分别位a,b,c,d;
写成:num = 1000*a + 100*b + 10*c + d = (999*a + 99*b + 9*c )+ (a + b + c +d)
num除以9的余数等于(a+b+c+d)除以9余数结果一样

#!/usr/bin/env python
# encoding:utf-8
"""
__author__:adam
功能:非负整数各位相加
第一种方法
"""

class Solution(object):
    def addDigits(self,num):
        """
        :type num:str
        :type :int
        """
        return 1 + (num -1) % 9;[参考链接](https://blog.csdn.net/xy010902100449/article/details/49046199)
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐