소프트웨어에 대한 모든 것

LeetCode 풀기 - 258. Add Digits 본문

알고리즘/LeetCode

LeetCode 풀기 - 258. Add Digits

앤테바 2022. 2. 8. 20:27
반응형

258. Add Digits

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

 

Add Digits - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제)

솔루션1) Straight-forward

class Solution:
    def addDigits(self, num: int) -> int:
        num_to_sumnum = lambda num: sum(int(n) for n in str(num))
        
        while True:
            num = num_to_sumnum(num)
            if num < 10: return num

솔루션2)

시간 복잡도 : O(1)

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

 

반응형
Comments