Skip to content

Commit

Permalink
2. Add Two Numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
gzc authored Jan 29, 2022
1 parent be10ef7 commit c18a8b0
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions scala/0001-0010/Add Two Numbers.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* Definition for singly-linked list.
* class ListNode(_x: Int = 0, _next: ListNode = null) {
* var next: ListNode = _next
* var x: Int = _x
* }
*/
object Solution {
def addTwoNumbers(l1: ListNode, l2: ListNode): ListNode = {
def addTwoNumbersHelper(l1: ListNode, l2: ListNode, carry: Int): ListNode = {
if (l1 == null && l2 == null) if (carry == 0) null else ListNode(carry)
else if (l1 == null) addTwoNumbersHelper(ListNode(0), l2, carry)
else if (l2 == null) addTwoNumbersHelper(l1, ListNode(0), carry)
else ListNode((l1.x + l2.x + carry) % 10, addTwoNumbersHelper(l1.next, l2.next, (l1.x + l2.x + carry) / 10 ))
}

addTwoNumbersHelper(l1, l2, 0)
}
}

0 comments on commit c18a8b0

Please sign in to comment.