-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path002.rb
More file actions
55 lines (48 loc) · 1.04 KB
/
002.rb
File metadata and controls
55 lines (48 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val)
# @val = val
# @next = nil
# end
# end
# @param {ListNode} l1
# @param {ListNode} l2
# @return {ListNode}
def add_two_numbers(l1, l2)
result = nil
result_tail = nil
node_on_l1 = l1
node_on_l2 = l2
overflow = 0
while !node_on_l1.nil? || !node_on_l2.nil? do
sum = 0
if node_on_l1.nil?
sum = node_on_l2.val
elsif node_on_l2.nil?
sum = node_on_l1.val
else
sum = node_on_l1.val + node_on_l2.val
end
sum += overflow
if sum >= 10
overflow = 1
sum -= 10
else
overflow = 0
end
if result.nil?
result = ListNode.new(sum)
result_tail = result
else
result_tail.next = ListNode.new(sum)
result_tail = result_tail.next
end
node_on_l1 = node_on_l1.next unless node_on_l1.nil?
node_on_l2 = node_on_l2.next unless node_on_l2.nil?
end
if overflow == 1
result_tail.next = ListNode.new(overflow)
end
result
end