【leetcode】【数论】258.Add Digit (python)

本文介绍了一种快速求解数字根的方法,通过观察规律发现,当n为非零正整数时,其数字根可通过公式res=1+(n-1)%9计算得出,特别地,当n为0时,其数字根为0。这种方法避免了繁琐的循环计算过程,大大提高了计算效率。

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

题目描述
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
给定一个非负整数,重复将其每位数相加,直到结果只有一位数为止。

思路一
采用最简单的循环计算方法,但是这样不符合题目要求。

class Solution:
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        while True:
            m = 0
            while num > 0:
                m += num % 10
                num //= 10
            if m < 10:
                return m
            if m >= 10:
                num = m

思路二
观察规律,1,2,3…9的数根分别为1,2,3…9。10,11,12…18的数根也分别为1,2,3…9。由规律我们可以得到:
当n = 0时,res = 0;
当n > 0时,res = 1+(n-1) mod 9

代码

class Solution:
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        if num == 0:
            return 0
        else:
            return 1 + (num-1) % 9
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值