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)
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
分析:
两个数由低位到高位存放在两个链表里,求两数之和。
还是求余进位的典型题目。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//check para
if(l1==null || l2==null)
return null;
ListNode head = new ListNode(0);
ListNode tail = head;
int a,b,res,digit;
int carry = 0;
while(l1 != null || l2 !=null){
if(l1 == null){
a = 0; b = l2.val;
l2 = l2.next;
}else if(l2 == null){
a = l1.val; b = 0;
l1 = l1.next;
}else{
a= l1.val; b = l2.val;
l1 = l1.next;
l2 = l2.next;
}
res = a+b+carry;
digit = res%10;
carry = res/10;
tail.next = new ListNode(digit);
tail = tail.next;
}
if(carry != 0)
tail.next = new ListNode(carry);
return head.next;
}
}