컴퓨터공학/알고리즘 문제 풀이

[LeetCode] 989. Add to Array-Form of Integer

TaeGyeong Lee 2023. 2. 15. 15:13

https://leetcode.com/problems/add-to-array-form-of-integer

 

Add to Array-Form of Integer - LeetCode

Add to Array-Form of Integer - The array-form of an integer num is an array representing its digits in left to right order. * For example, for num = 1321, the array form is [1,3,2,1]. Given num, the array-form of an integer, and an integer k, return the ar

leetcode.com

접근

  • 정수 배열인 num 을 정수로 바꾸어 num 과 k의 합을 계산
  • 계산한 값을 다시 정수 배열로 반환

한계

  • 이 문제는 위의 접근으로 풀도록 설계된 것이 아님
  • 각 인덱스 비교, 합산을 통해 carry 값을 반영시키는 것이 핵심
  • 다음에 다시 의도 방식대로 풀어볼 것

솔루션1 (비추천)

class Solution:
    def addToArrayForm(self, num: List[int], k: int) -> List[int]:
        num_length = len(num)
        # get num as integer
        num_int = sum(
            value * (10 ** (num_length - index -1)) 
            for index, value in enumerate(num))

        # get sum of num and k
        answer_str = str(num_int + k)
        answer = [int(i) for i in answer_str]
        
        return answer