You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Java Solution
/* 2 -> 4 -> 3 5 -> 6 -> 4 7 0 8 */ public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode fake = new ListNode(0); ListNode p = fake; ListNode p1 = l1; ListNode p2 = l2; int carry = 0; while(p1!=null || p2!=null){ int sum = carry; if(p1!=null){ sum += p1.val; p1 = p1.next; } if(p2!=null){ sum += p2.val; p2 = p2.next; } if(sum>9){ carry=1; sum = sum-10; }else{ carry = 0; } ListNode l = new ListNode(sum); p.next = l; p = p.next; } //don't forget check the carry value at the end if(carry > 0){ ListNode l = new ListNode(carry); p.next = l; } return fake.next; } |
What if the digits are stored in regular order instead of reversed order?
Answer: We can simple reverse the list, calculate the result, and reverse the result.
package com.sekt.lambdaexp;
import java.util.LinkedList;
public class AddTwoNumbersLL2 {
public static void main(String[] args) {
LinkedList linkedList1 = new LinkedList();
LinkedList linkedList2 = new LinkedList();
linkedList1.add(9);
linkedList2.add(9);
linkedList2.add(9);
linkedList2.add(9);
AddTwoNumbersLL2 ll2 = new AddTwoNumbersLL2();
LinkedList res = ll2.addTowNumbers(linkedList1, linkedList2);
System.out.println(res.toString());
}
public LinkedList addTowNumbers(LinkedList l1, LinkedList l2) {
LinkedList res = new LinkedList();
LinkedList p1 = l1;
LinkedList p2 = l2;
int carry = 0;
while(p1.peek() != null || p2.peek() != null) {
int sum = carry;
if(p1.peek() != null) {
sum += p1.pollFirst();
}
if(p2.peek() != null) {
sum += p2.pollFirst();
}
if(sum > 9 ) {
carry = sum/10;
sum = sum % 10;
} else {
carry = 0;
}
res.add(sum);
}
if(carry > 0) {
res.add(carry);
}
return res;
}
}
The fake idea is nice.
I think the following solution is more readbale.
Node addNumbers(Node a, Node b)
{
Node startFake = new Node();
Node highest = startFake;
int carry = 0;
while(a != null || b != null || carry == 1)
{
int calc = carry +
(a == null ? 0 : a.digit) +
(b == null ? 0 : b.digit);
carry = calc / 10;
highest.next = new Node(calc % 10);
highest = highest.next;
}
return startFake.next;
}
package com.developerslike;
import java.util.LinkedList;
public class LinkedListSUM {
public static void main(String[] args) {
LinkedList linkedList1 = new LinkedList();
LinkedList linkedList2 = new LinkedList();
LinkedList linkedList3 = new LinkedList();
linkedList1.add(2);
linkedList1.add(4);
linkedList1.add(3);
linkedList2.add(5);
linkedList2.add(6);
linkedList2.add(4);
linkedList3 = addTwoLists(linkedList1,linkedList2);
linkedList3.forEach(a -> System.out.print(" "+a));
}
private static LinkedList addTwoLists(LinkedList l1, LinkedList l2) {
int carry =0;
LinkedList l3 = new LinkedList();
for(int i=l1.size()-1;i>=0;i--) {
int parseInt = Integer.parseInt(l1.get(i).toString());
int parseInt2 = Integer.parseInt(l2.get(i).toString());
int sum =parseInt + parseInt2+carry;
int value=sum%10;
carry =sum/10;
l3.add(value);
}
return l3;
}
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
int len1=0,len2=0,sum,rem=0;
struct ListNode *t1=l1,*t2=l2;
while(t1 || t2)
{
if(t1)
{
len1++;
t1=t1->next;
}
if(t2)
{
len2++;
t2=t2->next;
}
}
t1=l1,t2=l2;
if(len1>len2)
{
while(t2->next)
{
t2=t2->next;
}
while(len1>len2)
{
struct ListNode* new = (struct ListNode*)malloc(sizeof(struct ListNode));
new->val=0;
new->next=NULL;
t2->next=new;
t2=t2->next;
len2++;
}
}
if(len1next)
{
t1=t1->next;
}
while(len1val=0;
new->next=NULL;
t1->next=new;
t1=t1->next;
len1++;
}
}
t1=l1,t2=l2;
while(t1)
{
sum=t1->val+t2->val+rem;
t2->val=sum%10;
rem=sum/10;
t1=t1->next;
t2=t2->next;
}
if(rem)
{
t2=l2;
while(t2->next)
{
t2=t2->next;
}
struct ListNode* new = (struct ListNode*)malloc(sizeof(struct ListNode));
new->val=rem;
new->next=NULL;
t2->next=new;
}
return l2;
}
What if instead of initializing p and q (as l1 and l2 respectively) we directly use provided l1 and l2 instead? Would it create any difference?
Right. The first node can be detached, by fake.next = null. But it does not affect the correctness of the code.
ListNode result = fake.next;
fake.next = null;
First node in the solution will always be 0.
package structures;
public class AddTwoNumbers {
public LinkedList calculate(LinkedList first, LinkedList second) {
int carryOver = 0;
LinkedList result = new LinkedList();
Node firstCurrent = first.getHead();
Node secondCurrent = second.getHead();
while (firstCurrent != null && secondCurrent != null) {
int res = firstCurrent.getVal() + secondCurrent.getVal() + carryOver;
firstCurrent = firstCurrent.getNext();
secondCurrent = secondCurrent.getNext();
result.add(res % 10);
carryOver = carry(res);
}
while (firstCurrent != null) {
int res = carryOver + firstCurrent.getVal();
result.add(res% 10);
carryOver = carry(res);
}
while (secondCurrent != null) {
int res = carryOver + secondCurrent.getVal();
result.add(res% 10);
carryOver = carry(res);
}
return result;
}
private int carry(int res) {
int carryOver;
if (res > 9) {
carryOver = 1;
} else {
carryOver = 0;
}
return carryOver;
}
}
Работа в интернете
public static LinkedList addTwo(LinkedList l1,LinkedList l2){
LinkedList res= new LinkedList();
int carry=0;
while(l1.size()!=0&&l2.size()!=0){
int x=(int)l1.removeFirst()+(int)l2.removeFirst()+carry;
int r=(x)%10;
carry=(x)/10;
res.add(r);}
while(l1.size()!=0){
int x=(int)l1.removeFirst()+carry;
int r=(x)%10;
carry=(x)/10;
res.add(r);}
while(l2.size()!=0){
int x=(int)l2.removeFirst()+carry;
int r=(x)%10;
carry=(x)/10;
res.add(r);}
if(carry==1)
res.add(carry);
return res;}
public static LinkedList addNumbers(LinkedList l1, LinkedList l2){
LinkedList result = new LinkedList();
int value=0;
int carry=0;
Node iterator1 = l1.getHead();
Node iterator2 = l2.getHead();
while(iterator1!=null && iterator2 !=null){
value=iterator1.getValue()+iterator2.getValue();
//checking if it is the last node of the list
// and if the sum needs another node.
if(iterator1.getPointer()==null && value+carry>9){
result.insertLast((value+carry)%10);
result.insertLast(1);
}
else{
result.insertLast((value+carry)%10);
if(value+carry>9)
carry=1;
else
carry=0;
}
iterator1=iterator1.getPointer();
iterator2=iterator2.getPointer();
}
return result;
}
public static LinkedList addNumbers(LinkedList l1, LinkedList l2){
LinkedList result = new LinkedList();
int value=0;
int carry=0;
Node iterator1 = l1.getHead();
Node iterator2 = l2.getHead();
while(iterator1!=null && iterator2 !=null){
value=iterator1.getValue()+iterator2.getValue();
//checking if it is the last node of the list
// and if the sum needs another node.
if(iterator1.getPointer()==null && value+carry>9){
result.insertLast((value+carry)%10);
result.insertLast(1);
}
else{
result.insertLast((value+carry)%10);
if(value+carry>9)
carry=1;
else
carry=0;
}
iterator1=iterator1.getPointer();
iterator2=iterator2.getPointer();
}
return result;
}
This might not work in the case when you add 1 and 0. Probably do if (p1.val+p2.val )>9.
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry = 0;
int num = 0;
ListNode r = null;
ListNode head = null;
while (l1 != null || l2 != null) {
if (l1 != null && l2 != null) {
num = l1.val + l2.val;
l1 = l1.next;
l2 = l2.next;
} else if (l1 != null) {
num = l1.val;
l1 = l1.next;
} else if (l2 != null) {
num = l2.val;
l2 = l2.next;
}
if ((num + carry) >= 10) {
num = (num + carry) - 10;
carry = 1;
} else {
num = num + carry;
carry = 0;
}
if (r == null) {
r = new ListNode(num);
head = r;
} else {
ListNode l = new ListNode(num);
r.next = l;
r = r.next;
}
}
if (carry != 0) {
ListNode l = new ListNode(carry);
r.next = l;
}
return head;
}
You could do it, but its not a good practice to navigate the list with the head pointers.
Works for all the cases, you are just changing the order of numbers and adding it in the same way. Eg: 490 +829 = 1319. Using this method gives 094+928 = 9131 which is correct (Reverse of 9131 is 1319)
A slightly simpler version,
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int reminder = 0, sum = 0, nextDigit = 0;
ListNode dummyNode = new ListNode(0);
ListNode T = dummyNode;
while (l1 !=null && l2 != null){
sum = l1.val+l2.val+reminder;
nextDigit = sum > 9 ? sum-10 : sum;
reminder = sum > 9 ? 1 : 0;
T.next = new ListNode(nextDigit);
l1=l1.next;
l2=l2.next;
T=T.next;
}
while (l1 !=null){
sum = l1.val+reminder;
nextDigit = sum > 9 ? sum-10 : sum;
reminder = sum > 9 ? 1 : 0;
l1=l1.next;
T.next = new ListNode(nextDigit);
T=T.next;
}
while (l2 !=null){
sum = l2.val+reminder;
nextDigit = sum > 9 ? sum-10 : sum;
reminder = sum > 9 ? 1 : 0;
l2=l2.next;
T.next = new ListNode(nextDigit);
T=T.next;
}
if (reminder != 0 )
T.next = new ListNode(reminder);
return dummyNode.next;
}
Thanks for the code.. Logically its correct. The only concern is about adding a 4 digit number to a 3 digit number in regular order
I am also curious about that. Did you figure it out?
Bunch of looser have you guys tested it once ?
it wasted my 50 min of time.
Doesn’t work if first two numbers added together are >= 10 does it?
I wonder, why do you need a new name for l1 and l2 and don’t just use l1 and l2?
In this case an additional ListNode is added at the end of resulting sum. The following excerpt solves the case:
if(carry==1)
p3.next=new ListNode(1);
What if you get 4 digits after adding two 3-digit numbers?