給出兩個 非空 的鏈表用來表示兩個非負的整數。其中,它們各自的位數是按照 逆序 的方式存儲的,並且它們的每個節點只能存儲 一位 數字。
如果,我們將這兩個數相加起來,則會返回一個新的鏈表來表示它們的和。
您可以假設除了數字 0 之外,這兩個數都不會以 0 開頭。
示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 輸出:7 -> 0 -> 8 原因:342 + 465 = 807
第一次看這個題是四個月前,當時想的是轉成兩個數字然後相加,然後寫出了果然不行。今天再看一眼就是模擬進位加法。逆序的還是比較簡單,先寫逆序的。
/**
* 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 head=new ListNode(0);
ListNode n1=l1;
ListNode n2=l2;
ListNode cur=head;
int carry=0;
while(n1!=null||n2!=null){
int num1= (n1!=null)?n1.val:0;
int num2= (n2!=null)?n2.val:0;
cur.val=num1+num2+carry;
carry=cur.val/10;
cur.val%=10;
if(n1!=null)n1=n1.next;
if(n2!=null)n2=n2.next;
if(n1!=null||n2!=null){
cur.next=new ListNode(0);
cur=cur.next;
}
}
if(carry>0){
cur.next=new ListNode(carry);
}
return head;
}
}
執行用時: 33 ms, 在Add Two Numbers的Java提交中擊敗了89.76% 的用戶