刷刷刷LeetCode(一) : 相加兩數

LUFOR129

--

由於被教授逼著刷LeetCode,所以想寫個文章來激勵自己刷題,LeetCode的題我大部分不會做啦,所以寫一些感覺蠻有趣的題目。

You are given two non-empty linked lists representing two non-negative integers. 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.

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.

這個大概是LeetCode 最簡單的中級題了,寫完了後以後就沒有這麼簡單的題了,嚶嚶嚶。這題只有1個難點: 如何進位?

程式定義好的數據結構:

/**
* 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 LL=new ListNode(0); //建立頭結點
ListNode ans=LL;
while(l1!=null&&l2!=null){
LL.next=new ListNode(l1.val+l2.val); //相加
LL=LL.next;
l1=l1.next;
l2=l2.next;
}
if(l1!=null){
LL.next=l1;
}
if(l2!=null){
LL.next=l2;
}
ans=ans.next;
}
}

接下來把ans節點中 val >10 ,進位。 !! 注意,當ans 進位>ans.length 時,建立新結點。

while(ans!=null){
if(ans.val>=10){
if(ans.next==null){
ans.next=new ListNode(1);
}else{
ans.next.val+=1;
}
}
ans.val=ans.val%10;
ans=ans.next;
}

完整代碼如下:

--

--