码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode&Python] Problem 258. Add Digits

时间:2018-10-31 13:58:54      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:you   object   highlight   any   NPU   Plan   follow   leetcode   sel   

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(object):
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        s=str(num)
        while len(s)>1:
            n=0
            for i in s:
               n+=int(i)
            s=str(n)
            
        return int(s)

  

[LeetCode&Python] Problem 258. Add Digits

标签:you   object   highlight   any   NPU   Plan   follow   leetcode   sel   

原文地址:https://www.cnblogs.com/chiyeung/p/9882339.html

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