[LeetCode] 2. Add Two Numbers

[LeetCode] 2. Add Two Numbers

Kotlin

자리올림(carry) 이용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
fun ListNode.value() = this?.`val` ?: 0

fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
var (list1, list2) = l1 to l2
var head = ListNode(0)
var cur = head
var carry = 0

while (list1 != null || list2 != null || carry > 0) {
val x = list1?.value() ?: 0
val y = list2?.value() ?: 0
val sum = (x + y + carry) % 10
carry = (x + y + carry) / 10
cur?.next = ListNode(sum)
cur = cur.next
if (list1 != null) list1 = list1.next
if (list2 != null) list2 = list2.next
}
return head.next
}
}
1
2
Runtime: 240 ms, faster than 18.40% of Kotlin online submissions for Add Two Numbers.
Memory Usage: 43.6 MB, less than 11.74% of Kotlin online submissions for Add Two Numbers.

댓글