관리 메뉴

솜씨좋은장씨

[leetCode] 258. Add Digits (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 258. Add Digits (Python)

솜씨좋은장씨 2020. 10. 8. 19:36
728x90
반응형

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.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

 

Solution

class Solution:
    def addDigits(self, num: int) -> int:
        while True:
            if num // 10 < 1:
                return num
            
            num_list = list(map(int, list(str(num))))
            
            sum_num = sum(num_list)
            
            num = sum_num

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments