Skip to content

Instantly share code, notes, and snippets.

@carolinemusyoka
Created October 29, 2021 20:21
Show Gist options
  • Save carolinemusyoka/c9c50ffbbd49f873846183c1d58a0bba to your computer and use it in GitHub Desktop.
Save carolinemusyoka/c9c50ffbbd49f873846183c1d58a0bba to your computer and use it in GitHub Desktop.
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
class Solution {
fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
val head = ListNode(0)
var i = l1
var j = l2
var curr = head
var cnt = 0
while (j != null || i != null) {
val x = i?.`val` ?: 0
val y = j?.`val` ?: 0
val temp = x+y+cnt
cnt = temp/10
curr.next = ListNode(temp%10)
curr = curr.next
if (i != null) i = i?.next
if (j != null) j = j?.next
}
if (cnt > 0) {
curr.next = ListNode(cnt)
}
return head.next
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment