-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2_add_two_numbers.rb
66 lines (55 loc) · 1008 Bytes
/
2_add_two_numbers.rb
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
56
57
58
59
60
61
62
63
64
65
66
# frozen_string_literal: true
require_relative '../common/linked_list'
# https://leetcode.com/problems/add-two-numbers/
# @param {ListNode} l1
# @param {ListNode} l2
# @return {ListNode}
def add_two_numbers(l1, l2)
sum = ::ListNode.new
p = sum
add = 0
while !l1.nil? && !l2.nil?
a = l1.val
b = l2.val
s = a + b + add
if s > 9
s -= 10
add = 1
else
add = 0
end
p.next = ::ListNode.new(s)
p = p.next
l1 = l1.next
l2 = l2.next
end
if !l1.nil?
until l1.nil?
s = l1.val + add
if s > 9
s -= 10
add = 1
else
add = 0
end
p&.next = ::ListNode.new(s)
p = p&.next
l1 = l1.next
end
elsif !l2.nil?
until l2.nil?
s = l2.val + add
if s > 9
s -= 10
add = 1
else
add = 0
end
p&.next = ::ListNode.new(s)
p = p&.next
l2 = l2.next
end
end
p&.next = ::ListNode.new(1) if add == 1
sum.next
end