본문 바로가기
알고리즘

[Swift] LeetCode - 2. Add Two Numbers

by 고고 2022. 2. 15.

문제: https://leetcode.com/problems/add-two-numbers/

 

Add Two Numbers - 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

 

 

연결리스트 문제는 CustomStringConvertible을 익스텐션으로 해서 프린트해가며 풀고 있습니다. ㅎㅎ

import Foundation

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; }
}

extension ListNode: CustomStringConvertible {
    public var description: String {
        var result = ""
        var current = self
        
        while current != nil {
            result.append("\(current.val)-> ")
            if current.next == nil {
                return result
            }
            current = current.next!
        }
        
        return result
    }
}

class Solution {
    func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        var olim = 0
        var l1 = l1
        var l2 = l2
        let root = ListNode(0)
        var head = root
        
        while l1 != nil || l2 != nil ||  olim != 0 {
            var value = 0
            
            if l1 != nil {
                value += l1!.val
            }
            if l2 != nil {
                value += l2!.val
            }
            
            if olim != 0 {
                value += olim
                olim = 0
            }
            
            if value >= 10 {
                olim = value / 10
                value %= 10
            }
            
            head.next = ListNode(value)
            head = head.next!
            
            l1 = l1?.next
            l2 = l2?.next
        }
        
        return root.next
    }
}

let head1 = ListNode(9)
let node1 = ListNode(9)
let node2 = ListNode(9)
let node3 = ListNode(9)
let node4 = ListNode(9)
let node5 = ListNode(9)
let node6 = ListNode(9)
let node7 = ListNode(9)
head1.next = node1
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
node5.next = node6
node6.next = node7

let head2 = ListNode(9)
let node21 = ListNode(9)
let node22 = ListNode(9)
let node23 = ListNode(9)
let node24 = ListNode(9)
head2.next = node21
node21.next = node22
node22.next = node23
node23.next = node24

print(Solution().addTwoNumbers(head1, head2)) // [8,9,9,9,0,0,0,1]

댓글