<reponame>dmitrvk/solutions<filename>leetcode/add_two_numbers.py
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        result = _make_number(l1) + _make_number(l2)
        return _make_linked_list(_make_list(result))


def test_add_two_numbers():
    node = Solution().addTwoNumbers(
        _make_linked_list([2, 4, 3]),
        _make_linked_list([5, 6, 4]),
    )

    assert _make_number(_make_linked_list([2, 4, 3])) == 342
    assert _make_list(342) == [2, 4, 3]

    assert node.val == 7
    assert node.next.val == 0
    assert node.next.next.val == 8


def _make_linked_list(numbers: list) -> ListNode:
    node = None

    for number in reversed(numbers):
        node = ListNode(number, node)

    return node


def _make_number(node: ListNode) -> int:
    number = 0
    multiplier = 1

    while True:
        number += node.val * multiplier
        multiplier *= 10
        node = node.next

        if node is None:
            break

    return number


def _make_list(number: int) -> list:
    digits = []
    digits_count = len(str(number))

    while digits_count > 0:
        digits.append(number % 10)
        number //= 10
        digits_count -= 1

    return digits
