/** * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ classSolution{ funaddTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? { if (l1==null||l2==null) returnnull
val numString = StringBuilder() var carry = 0 var link1:ListNode? = l1 var link2:ListNode? = l2 while (link1!=null||link2!=null){ val one = link1?.`val` ?: 0 val two = link2?.`val` ?: 0 var add = one+two+carry if (add>=10){ carry = 1 add %= 10 }else carry = 0 numString.append(add)
link1?.let { link1 = it.next } link2?.let { link2 = it.next } } if (carry==1) numString.append(1) val linkNode : ListNode = ListNode(numString[0].toInt()-48) var point = linkNode for (i in1 until numString.length){ val node = ListNode(numString[i].toInt()-48) point.next = node point = node } point.next = null return linkNode } }