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

(LeetCode)Add Digits --- 整数各位相加

时间:2016-08-02 11:45:53      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:

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 = 111 + 1 = 2. Since 2 has only one digit, return it.

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


解题分析:

解法一:

  对num求余,相加,求余相加,直到num小于两位数。

# -*- coding:utf-8 -*-
__author__ = 'jiuzhang'
class Solution(object):
    def addDigits(self, num):
        while num >= 10:
            num = (num / 10) + num % 10
        return num


解法二:

另一个方法比较简单,可以举例说明一下。假设输入的数字是一个5位数字num,

则num的各位分别为a、b、c、d、e。有如下关系:num = a * 10000 + b * 1000 + c * 100 + d * 10 + e

即:num = (a + b + c + d + e) + (a * 9999 + b * 999 + c * 99 + d * 9)

因为 a * 9999 + b * 999 + c * 99 + d * 9 一定可以被9整除,因此num模除9的结果

与 a + b + c + d + e 模除9的结果是一样的。对数字 a + b + c + d + e 反复执行同类操作,

最后的结果就是一个 1-9 的数字加上一串数字,最左边的数字是 1-9 之间的,右侧的数字永远都

是可以被9整除的。

注意:

要处理特殊情况,当数为 0 时候,请直接返回0


# -*- coding:utf-8 -*-
__author__ = 'jiuzhang'
class Solution(object):
    def addDigits(self, num):
        if num > 0:
            return 1 + (num - 1)% 9
        else:
            return 0



(LeetCode)Add Digits --- 整数各位相加

标签:

原文地址:http://blog.csdn.net/u012965373/article/details/52087780

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