본문 바로가기

알고리즘/LeetCode

AddDigit

Problem

  • Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.
  • 정수 값이 들어오면 정수값을 포함하고 있는 자리수의 모든 값들의 합이 하나만 남을때까지 반복하여 더하고 그 값을 반환하는 문제
  • 38 → 3 + 8 → 11 → 1 + 1 → 2 → return 2

Solution

class Solution:
    def addDigits(self, num: int) -> int:
        res = num
        while res > 9:
            res_list = list(str(res))
            result = 0
            for i in res_list:
                result += int(i)
                    
            res = result
        return res

Brute Force 방식

  • while문을 사용하여 정수 값이 9 이상이면 로직을 반복하도록 구성
  • 정수값을 리스트로 변환하기 위해 str으로 바꾼후 리스트로 변경 한다.
  • for문을 사용하여 값들을 순회하며 int형으로 형변환 후 result 변수에 값을 누적하고 res 값에 result를 넣어준다.
  • O(n)

9 나누어 처리 하는 방식

class Solution:
    def addDigits(self, num: int) -> int:
        if num == 0 : return 0
        if num % 9 == 0: return 9
        else : return (num % 9)
  • 간단하게 9로 나누어 값이 떨어지면 0을 리턴하고 나눈어 떨어지지 않으면, 9로 나눈 나머지 값을 리턴하면 된다.
  • O(1)

'알고리즘 > LeetCode' 카테고리의 다른 글

Counting Bits  (0) 2024.04.22
AddBinary  (0) 2024.04.14