Add Two Numbers

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 contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int carry = 0;
        ListNode current1 = l1, current2 = l2, ans = new ListNode(0);
        ListNode temp = ans;
        while (current1 != null || current2 != null) {
            int value = carry;
            if (current1 != null) {
                value += current1.val;
                current1 = current1.next;
            }
            if (current2 != null) {
                value += current2.val;
                current2 = current2.next;
            }
            carry = value / 10;
            value = value % 10;
            temp.next = new ListNode(value);
            temp = temp.next;
        }
        if (carry != 0) {
            ListNode last = new ListNode(carry);
            temp.next = last;
        }
        return ans.next;
    }
}

Last updated