码迷,mamicode.com
首页 > 其他好文 > 详细

258. Add Digits

时间:2018-10-05 13:55:26      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:exp   result   ret   ati   ike   self   xpl   input   code   

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

Example:

Input: 38
Output: 2
Explanation: 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?

class Solution:
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        while True:
            n = 0
            for i in str(num):
                n += int(i)
            if n<10 and n>=0:
                return n
            num = n

O(1) solution:

class Solution:
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        if num == 0:
            return 0
        t = num % 9 
        return t if t else 9

没啥意思,找规律的题。

258. Add Digits

标签:exp   result   ret   ati   ike   self   xpl   input   code   

原文地址:https://www.cnblogs.com/bernieloveslife/p/9741893.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!