Kotlin Leetcode - 2. Add Two Numbers
class Solution {
fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
}
}
解題思路
本題練習的是針對 linked list 的操作
在 Kotlin 解題需要注意的是 val 是關鍵字
所以需要 以 `` 標記
Kotlin 參考解答
點擊展開解答
class Solution {
fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
val head = ListNode(0)
var cursor = head
var node1 = l1
var node2 = l2
var carry = 0
while (node1 != null || node2 != null) {
val sum = (node1?.`val` ?: 0) + (node2?.`val` ?: 0) + carry
cursor.next = ListNode(sum % 10)
cursor = cursor.next
carry = if (sum > 9) 1 else 0
if (node1 != null) node1 = node1?.next
if (node2 != null) node2 = node2?.next
}
if (carry > 0) {
cursor.next = ListNode(carry)
cursor = cursor.next
}
return head?.next
}
}
回到 leetcode 列表