We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
2 parents 0301c77 + dc1c0af commit 2523409Copy full SHA for 2523409
ruby/2-Add-Two-Numbers.rb
@@ -0,0 +1,33 @@
1
+# Definition for singly-linked list.
2
+# class ListNode
3
+# attr_accessor :val, :next
4
+# def initialize(val = 0, _next = nil)
5
+# @val = val
6
+# @next = _next
7
+# end
8
9
+# @param {ListNode} l1
10
+# @param {ListNode} l2
11
+# @return {ListNode}
12
+def add_two_numbers(l1, l2)
13
+ dummy_head = ListNode.new()
14
+ curr = dummy_head
15
+
16
+ carry = 0
17
+ while l1 || l2 || carry > 0
18
+ l1_val = l1 ? l1.val : 0
19
+ l2_val = l2 ? l2.val : 0
20
21
+ sum = l1_val + l2_val + carry
22
+ ones = sum % 10
23
+ carry = sum / 10
24
25
+ curr.next = ListNode.new(ones)
26
27
+ curr = curr.next
28
+ l1 = l1.next if l1
29
+ l2 = l2.next if l2
30
+ end
31
32
+ dummy_head.next
33
+end
0 commit comments