LeetCode258. Add Digits

本文探讨了将非负整数反复累加直至只剩一位数的算法实现。提供了三种方法:字符串转换累加、纯数字计算及巧妙利用模运算特性。深入解析了每种方法的优劣,并给出具体Python代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

 思路:这个题方法有很多,大体思路是把数字转化为字符串,再分别转为数字相加,再转为字符串...其中判定结束的方法可以是数字小于10,也可以是数字长度等于1.

class Solution(object):
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        l = len(str(num))
        
        if l == 1:
            return num
        
        sum = 0
        for i in str(num):
            sum += int(i)
        
        return self.addDigits(sum)

当然也可以只靠数字计算

  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

还有一种比较聪明的方法,因为

1 % 9 = 1

10 % 9 = 1

100 % 9 = 1

所以N % 9 = a[0] + a[1] + ..a[n](除了N%9=0的时候)

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值