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.
Solution with Runtime 108 ms.
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode result = head;
var flag = 0;
while(l1 != null || l2 != null){
var num = 0;
if(l1 != null && l2 != null){
num = l1.val + l2.val;
l1 = l1.next;
l2 = l2.next;
}
else if(l1 != null && l2 == null){
num = l1.val;
l1 = l1.next;
}
else if(l1 == null && l2 != null){
num = l2.val;
l2 = l2.next;
}
if( flag == 1 ){
num++;
}
if(num > 9){
num = num % 10;
flag = 1;
}
else
flag = 0;
ListNode current = new ListNode(num);
head.next = current;
head = current;
}
if( flag == 1 ){
head.next = new ListNode(1);
}
return result.next;
}
}
We can simplify the solution a bit more.
- define val as an adder for each digit (l1.value + l2.value), if bigger than 10, use (val % 10) for current result node value, yet return (val / 10) before next round addition;
- termination condition: while l1 or l2 is not null, also if val is not ZERO, keep addition
Solution 2: A better and easy understanding solution
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode result = head;
int val = 0;
while(l1 != null || l2 != null || val != 0){
if(l1 != null){
val += l1.val;
l1 = l1.next;
}
if(l2 != null){
val += l2.val;
l2 = l2.next;
}
head.next = new ListNode(val % 10);
head = head.next;
val = val / 10;
}
return result.next;
}
}