250x250
반응형
Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

개발자 수니

[LeetCode/Swift] 2. Add Two Numbers 본문

Algorithm

[LeetCode/Swift] 2. Add Two Numbers

개발자 수니 2024. 1. 16. 16:51
728x90
반응형

💡 문제 (Medium)

 

LeetCode - The World's Leading Online Programming Learning Platform

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

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

두 개의 양의 정수를 나타내는 비어 있지 않은 두 링크드 리스트가 제공됩니다. 각 숫자는 역순으로 저장되어 있으며, 각 노드는 한 자리 숫자를 포함합니다. 두 숫자를 더하고 합계를 링크드 리스트로 반환하세요.

 

Example 1:

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.

Example 2:

Input: l1 = [0], l2 = [0]
Output: [0]

Example 2:

Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]

Constraints:

  • The number of nodes in each linked list is in the range [1, 100].
  • 0 <= Node.val <= 9
  • It is guaranteed that the list represents a number that does not have leading zeros.

👩🏻‍💻 해결

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init() { self.val = 0; self.next = nil; }
 *     public init(_ val: Int) { self.val = val; self.next = nil; }
 *     public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
 * }
 */

 

1차 class 변수로 carry(올림값)을 선언하여 재귀 함수로 풀이

class Solution {
    var carry: Int = 0
    
    func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        if l1 == nil, l2 == nil, carry == 0 { return nil }

        let sum = (l1?.val ?? 0) + (l2?.val ?? 0) + carry
        carry = sum / 10

        return .init(sum % 10, addTwoNumbers(l1?.next, l2?.next))
    }
}

 

2차 반복문을 사용하여 풀이

class Solution {
    func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        var l1 = l1
        var l2 = l2
        var prev: ListNode?
        var carry = 0
        var result: ListNode?

        while l1 != nil || l2 != nil || carry != 0 {
            let sum = (l2 == nil ? 0 : l2!.val) + (l1 == nil ? 0 : l1!.val) + carry
            carry = sum / 10

            let new = ListNode(sum % 10)
            prev?.next = new
            prev = new

            if result == nil {
                result = new
            }

            l1 = l1 == nil ? l1: l1?.next
            l2 = l2 == nil ? l2: l2?.next
        }

        return result
    }
}

 

728x90
반응형
Comments