Python实现"各位相加"的两种方法

给定一个非负整数num,重复累加num中的每一个数字直至结果为个位数

Input: 38
Output: 2 
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
Since 2 has only one digit, return it

进阶:

不用循环或者递归,并且时间复杂度为O(1)

1:不停循环累加,直至结果小于10

def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        while num>9:
            newNum = 0
            for i in str(num):
                newNum += int(i)
            num = newNum
        return num

2:(13)%9=(1*10+3)%9=(1*9+1+3)%9=(1+3)%9 故:(ab)%9=(a+b)%9(参考他人代码)

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

算法题来自:https://leetcode-cn.com/problems/add-digits/description/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值