258. Add Digits -- 递归、字符串分解

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?

解一:
看到这个题目,想到的是递归,因为这个模式就是反复的执行同一件事情,一直下去直到停止条件。
这里的停止条件就是只有一位数的时候。
这里使用了reduce进行数字的加法运算,现在想想好像直接一个sum()也是可以解决的。
然后使用了列表解析,先将数值型转换成字符串,然后再将字符串分解,再转换为数值型。

class Solution(object):
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """

        if len(str(num)) == 1:
            return num
        return self.addDigits(reduce(operator.add, [int(i) for i in str(num)]))

解二:
使用了循环,并且取余和除相结合取出每个位置上的数值。

      class Solution(object):
      def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        while(num >= 10):
            temp = 0
            while(num > 0):
                temp += num % 10
                num /= 10
            num = temp
        return num
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值