zl程序教程

您现在的位置是:首页 >  其他

当前栏目

每日一题 ---258. 各位相加[力扣][Go]

2023-03-14 23:00:23 时间

题目:

给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。返回这个结果。

解题代码:

func addDigits(num int) int {
    ans := 0
    for {
        for num > 0{
            ans += num%10
            num = num/10
        }
        if ans < 10 {
            break
        }
        num = ans
        ans = 0
    }
    return ans
}

image