알고리즘/leetcode

258. Add Digits

1.5볼트 2023. 4. 26. 19:43
728x90

https://leetcode.com/problems/add-digits/description/

 

Add Digits - LeetCode

Can you solve this real interview question? Add Digits - Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.   Example 1: Input: num = 38 Output: 2 Explanation: The process is 38 --> 3 + 8 --> 11 11 -->

leetcode.com

 

숫자 자릿수 합 -> 10 이상이면 다시
숫자 자릿수 합 -> 10 이상이면 다시
반복 10 보다 작아질 때까지

 

class Solution:
    def addDigits(self, num: int) -> int:
        def f(x):
            t=0
            while x>0:
                t+=x%10
                x//=10
            return t
        while num>=10:
            num=f(num)
        return num