258. Add Digits [easy] (Python)

题目链接

https://leetcode.com/problems/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?

题目翻译

给定一个非负整数,将该整数的所有数字的和作为新的整数,重复直至得到只有一个数的整数。
比如:给定num=38,上述过程为:3 + 8 = 11, 1 + 1 = 2。因为2只有一个数字,所以返回2。
进一步:你能不用迭代或循环,在O(1)时间解决该问题吗?

思路方法

Hint:
1. A naive implementation of the above process is trivial. Could you come up with other methods?
2. What are all the possible results?
3. How do they occur, periodically or randomly?
4. You may find this Wikipedia article useful.

思路一

先不考虑“进一步”,根据定义来循环计算,效率低,但是可以AC。

代码

class Solution(object):
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        while num > 9:
            s = 0
            while num >= 1:
                s += num%10
                num /= 10
            num = s
        return num

思路二

根据提示,当输入从1到100变化时,可以发现,输出在“1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,…”这样循环。于是,就有了下面O(1)的算法。
dr(n) = 0, if n = 0
dr(n) = 9, if n != 0 and n mod 9 == 0
dr(n) = n mod 9, if n mod 9 != 0
或,
dr(n) = 1 + (n-1) mod 9

这个问题又叫做“digit root”问题,参看:
https://en.wikipedia.org/wiki/Digital_root#Congruence_formula

代码一

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

代码二

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

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51378231

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值