JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

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.

Code

class Solution {
    public int addDigits(int num) {
        if(num < 10) return num;

        int res = 0;

        while(num != 0) {
            res += num % 10;
            num /= 10;
        }

        return addDigits(res);
    }
}
class Solution:
    def addDigits(self, num: int) -> int:
        if num < 10:
            return num

        res = 0
        while num != 0:
            res += num % 10
            num //= 10

        return self.addDigits(res)

digit root 问题

class Solution:
    def addDigits(self, num: int) -> int:
        return 0 if num == 0 else (num - 1) % 9 + 1