문제: https://leetcode.com/problems/add-two-numbers/
연결리스트 문제는 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]
'알고리즘' 카테고리의 다른 글
[Swift] LeetCode - 641. Design Circular Deque (0) | 2022.02.16 |
---|---|
[Swift] LeetCode - 20. Valid Parentheses (0) | 2022.02.15 |
[Swift] LeetCode - 49. Group Anagrams (0) | 2022.02.14 |
[Swift] LeetCode - 819. Most Common Word (0) | 2022.02.14 |
[Swift] LeetCode - 937. Reorder Data in Log Files (0) | 2022.02.14 |
댓글