2 Add Two Numbers
You are given twonon-emptylinked lists representing two non-negative integers. The digits are stored inreverse orderand 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)
/**
* 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) {
ListNode result = new ListNode(-1);
ListNode current = result;
int carry = 0;
while (l1 != null || l2 != null) {
int num1 = 0, num2 = 0;
if (l1 != null) {
num1 = l1.val;
l1 = l1.next;
}
if (l2 != null) {
num2 = l2.val;
l2 = l2.next;
}
current.next = new ListNode((num1+num2+carry)%10);
current = current.next;
carry = (num1+num2+carry)/10;
}
if (carry > 0) {
current.next = new ListNode(carry);
}
return result.next;
}
}