Add Two Numbers

Problem:

You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.

Have you met this question in a real interview? Yes

Example
Given 7->1->6 + 5->9->2. That is, 617 + 295.

Return 2->1->9. That is 912.

Given 3->1->5 and 5->9->2, return 8->0->8.

Solution:

This is an easay problem. Use a carry varible to store the carray and go through the two list from right to left doing addtion.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*************************************************************************
> File Name: AddTwoNumbers.java
> Author: Yao Zhang
> Mail: psyyz10@163.com
> Created Time: Mon 16 Nov 12:07:30 2015
************************************************************************/


public class AddTwoNumbers{
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null && l2 == null)
return null;

int carry = 0;
ListNode head = new ListNode(0);
ListNode current = head;

while (l1 != null || l2 != null){
int sum = carry;

if (l1 != null){
sum += l1.val;
l1 = l1.next;
}
if (l2 != null){
sum += l2.val;
l2 = l2.next;
}

carry = sum / 10;
current.next = new ListNode(sum % 10);
current = current.next;
}

if (carry != 0){
current.next = new ListNode(carry);
}

return head.next;
}
}