[LeetCode][Python]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?

思路:

  1. 利用/和%运算可以得到num的每个数字,把各个数字的和加起来,如果比9大,继续使用该方法运算,直至各个数字的和小于9。但是好像不满足不使用loop的要求。
  2. 把数字用字符串表示,得到sum。
  3. 其他人的思路:abcde = 10000a + 1000b + 100c + 10d + e = (a + b + c + d + e) + 9999a + 999b +99c + 9d。所以用9去mod就行。如果结果是9,mod一下就变成0了,这道题里又不可能结果是0,所以mod前-1然后mod完+1就行
#!usr/bin/env  
# -*-coding:utf-8 -*-
class Solution(object):
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        if num <=9:
            return num

        sum = 0
        while(num):
            sum += num%10
            num= num/10

        return self.addDigits(sum)

    def addDigits2(self, num):
        return (num-1)%9 + 1

if __name__ == '__main__':
    sol = Solution()
    print sol.addDigits(38)
    print sol.addDigits(138)
    print sol.addDigits2(38)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容