Skip to content

Latest commit

 

History

History
41 lines (29 loc) · 1.14 KB

풀이_LC258.md

File metadata and controls

41 lines (29 loc) · 1.14 KB

😩 LeetCode 258. Add Digits

  • Date : 2021.08.29(일)
  • Time : 15분

Problem

  • Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.

Constraints

  • 0 <= num <= 2^31 - 1

Example

  • Input: num = 38
  • Output: 2
    Explanation: The process is
    38 --> 3 + 8 --> 11
    11 --> 1 + 1 --> 2 
    Since 2 has only one digit, return it.
    



풀이

    def addDigits(self, num: int) -> int:
        if num < 10 : return num

        str_num = str(num)

        sum = 0
        for i in str_num:
            sum += int(i)

        return self.addDigits(sum)
        

: 재귀함수를 사용한 문제! len(str(num)) > 1으로 if 문 검사를 할 수도 있었지만, 2자리 수가 되려면 10부터이기 때문에 10보다 작다는 것은 한자리 수라는 뜻이므로 이렇게 작성했다. num을 str화 하는 것도 메모리가 차지될테니깐..?! 그 다음에 if문을 통과했을 때 str(num)으로 문자열로 변경해주었다. 문자열로 변경한 이유는 한 숫자씩 for문을 이용해서 뽑아주기 위해서이다.