master
1def assert_equal(x, y)
2 raise [x, y].inspect unless x == y
3end
4
5class Node
6 attr_accessor :data, :next
7
8 def initialize(data)
9 @data = data
10 end
11
12 def to_s
13 "#{data}#{self.next&.to_s}"
14 end
15end
16
17class Solution
18 def self.run(l1, l2, carry = 0)
19 return Node.new(carry) if l1.nil? && l2.nil?
20 return l2 if l1.nil?
21 return l1 if l2.nil?
22
23 sum = l1.data + l2.data + carry
24 result = Node.new(sum % 10)
25 result.next = run(l1.next, l2.next, sum / 10);
26 result
27 end
28end
29
30l1 = Node.new(2)
31l1.next = Node.new(4)
32l1.next.next = Node.new(3)
33
34l2 = Node.new(5)
35l2.next = Node.new(6)
36l2.next.next = Node.new(4)
37
38result = Solution.run(l1, l2)
39assert_equal result&.data, 7
40assert_equal result&.next&.data, 0
41assert_equal result&.next&.next.data, 8
42
43l1 = Node.new(9)
44l1.next = Node.new(9)
45l1.next.next = Node.new(9)
46
47l2 = Node.new(9)
48l2.next = Node.new(9)
49l2.next.next = Node.new(9)
50
51result = Solution.run(l1, l2)
52assert_equal result&.data, 8
53assert_equal result&.next&.data, 9
54assert_equal result&.next&.next.data, 9
55assert_equal result&.next&.next&.next.data, 1
56
57l1 = Node.new(0)
58l1.next = Node.new(0)
59l1.next.next = Node.new(1)
60
61l2 = Node.new(0)
62
63result = Solution.run(l1, l2)
64assert_equal result&.data, 0
65assert_equal result&.next&.data, 0
66assert_equal result&.next&.next.data, 1
67=begin
68
69| 1 | 10 | 100 | 1000 |
70| 10^0 | 10^1 | 10^2 | 10^3 |
71| 2 | 4 | 3 |
72| 5 | 6 | 4 |
73
74x == (2 * 10^0) + (4 * 10^1) + (3 * 10^2)
75x == 342
76
77y == (5 * 10^0) + (6 * 10^1) + (4 * 10^2)
78y == 465
79
80=end
81
82puts "YAY!"