2. Add Two Numbers
Problem
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8Analysis
Code
/**
* Definition for singly-linked list.
* class ListNode(var `val`: Int = 0) {
* var next: ListNode? = null
* }
*/
class Solution {
fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
var listNode1 = l1
var listNode2 = l2
var carry = 0
var listNode: ListNode? = ListNode(0)
val head = listNode
while (listNode1 != null || listNode2 != null) {
carry = (listNode1?.`val` ?: 0) + (listNode2?.`val` ?: 0) + carry / 10
listNode?.next = ListNode(carry % 10)
listNode = listNode?.next
listNode1 = listNode1?.next
listNode2 = listNode2?.next
}
carry /= 10
if (carry != 0) {
listNode?.next = ListNode(carry)
}
return head?.next
}
}Last updated