Created
September 24, 2019 10:50
-
-
Save OmarKRostom/b4b7d85f5ec2de31d157fcedc386bfa9 to your computer and use it in GitHub Desktop.
Solution to two sums in kotlin (https://bit.ly/2GjpF4v)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun addTwoNumbers(l1: ListNode?, l2: ListNode?, nextNode: ListNode? = totalNode): ListNode? { | |
val firstVal = l1?.`val` ?: 0 | |
val secondVal = l2?.`val` ?: 0 | |
var total = firstVal + secondVal + (nextNode?.`val` ?: 0) | |
if (total >= 10) { | |
total = total.rem(10) | |
carryOn = 1 | |
} | |
nextNode?.`val` = total | |
nextNode?.next = ListNode(carryOn) | |
return if (l1?.next == null && l2?.next == null) { | |
if (carryOn == 0) nextNode?.next = null | |
totalNode | |
} else { | |
carryOn = 0 | |
addTwoNumbers(l1?.next, l2?.next, nextNode?.next) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment