|
| 1 | +[](https://github.com/LeetCode-in-Ruby/LeetCode-in-Ruby) |
| 2 | +[](https://github.com/LeetCode-in-Ruby/LeetCode-in-Ruby/fork) |
| 3 | + |
| 4 | +## 2\. Add Two Numbers |
| 5 | + |
| 6 | +Medium |
| 7 | + |
| 8 | +You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order**, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. |
| 9 | + |
| 10 | +You may assume the two numbers do not contain any leading zero, except the number 0 itself. |
| 11 | + |
| 12 | +**Example 1:** |
| 13 | + |
| 14 | + |
| 15 | + |
| 16 | +**Input:** l1 = [2,4,3], l2 = [5,6,4] |
| 17 | + |
| 18 | +**Output:** [7,0,8] |
| 19 | + |
| 20 | +**Explanation:** 342 + 465 = 807. |
| 21 | + |
| 22 | +**Example 2:** |
| 23 | + |
| 24 | +**Input:** l1 = [0], l2 = [0] |
| 25 | + |
| 26 | +**Output:** [0] |
| 27 | + |
| 28 | +**Example 3:** |
| 29 | + |
| 30 | +**Input:** l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] |
| 31 | + |
| 32 | +**Output:** [8,9,9,9,0,0,0,1] |
| 33 | + |
| 34 | +**Constraints:** |
| 35 | + |
| 36 | +* The number of nodes in each linked list is in the range `[1, 100]`. |
| 37 | +* `0 <= Node.val <= 9` |
| 38 | +* It is guaranteed that the list represents a number that does not have leading zeros. |
| 39 | + |
| 40 | +## Solution |
| 41 | + |
| 42 | +```ruby |
| 43 | +require_relative '../../com_github_leetcode/list_node' |
| 44 | + |
| 45 | +# Definition for singly-linked list. |
| 46 | +# class ListNode |
| 47 | +# attr_accessor :val, :next |
| 48 | +# def initialize(val = 0, _next = nil) |
| 49 | +# @val = val |
| 50 | +# @next = _next |
| 51 | +# end |
| 52 | +# end |
| 53 | +# @param {ListNode} l1 |
| 54 | +# @param {ListNode} l2 |
| 55 | +# @return {ListNode} |
| 56 | +def add_two_numbers(l1, l2) |
| 57 | + dummy_head = ListNode.new(0) |
| 58 | + p = l1 |
| 59 | + q = l2 |
| 60 | + curr = dummy_head |
| 61 | + carry = 0 |
| 62 | + |
| 63 | + while p || q |
| 64 | + x = p ? p.val : 0 |
| 65 | + y = q ? q.val : 0 |
| 66 | + sum = carry + x + y |
| 67 | + carry = sum / 10 |
| 68 | + curr.next = ListNode.new(sum % 10) |
| 69 | + curr = curr.next |
| 70 | + |
| 71 | + p = p.next if p |
| 72 | + q = q.next if q |
| 73 | + end |
| 74 | + |
| 75 | + curr.next = ListNode.new(carry) if carry > 0 |
| 76 | + |
| 77 | + dummy_head.next |
| 78 | +end |
| 79 | +``` |
0 commit comments