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;
}
}