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.
My Solution:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
boolean carry = false;
ListNode result = new ListNode(0);
ListNode p = result;
while(l1 != null || l2 != null){
int s = 0;
if(carry == true) {
s = 1;
carry = false;
}
int a = l1 == null ? 0 : l1.val;
int b = l2 == null ? 0 : l2.val;
s += a + b;
if(s >= 10) {
carry = true;
s %= 10;
}
p.next = new ListNode(s);
p = p.next;
if(l1 !=null)
l1 = l1.next;
if(l2 !=null)
l2 = l2.next;
}
if(carry) {
p.next = new ListNode(1);
}
return result.next;
}
}
Solution:
Intuition
Keep track of the carry using a variable and simulate digits-by-digits sum starting from the head of list, which contains the least-significant digit.
Figure 1. Visualization of the addition of two numbers: 342 + 465 = 807.
Each node contains a single digit and the digits are stored in reverse order.
Algorithm
Just like how you would sum two numbers on a piece of paper, we begin by summing the least-significant digits, which is the head of l1 and l2. Since each digit is in the range of 0…9, summing two digits may "overflow". For example 5 + 7 = 12