
https://leetcode.com/problems/add-two-numbers-ii/description/
445. Add Two Numbers II
給你兩個鏈表l1和l2,返回他們的相加(十進位加法),題目保證 l1 和 l2 不會是 0
開頭的數字(除了0)。
Example 1:
https://assets.leetcode.com/uploads/2021/04/09/sumii-linked-list.jpg
Input: l1 = [7,2,4,3], l2 = [5,6,4]
Output: [7,8,0,7]
Example 2:
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [8,0,7]
Example 3:
Input: l1 = [0], l2 = [0]
Output: [0]
思路:
1. 因為十進位加法要從右加到左(因為會產生進位),所以我們把鏈表 l1 和 l2 做反轉。
2. 將 l1 和 l2 做加法運算產生一個新的鏈表 l3。
3. 在得到解後需再將鏈表 l3 反轉,因為我們鏈表的連結方向和相加結果相反。
Java Code:
--------------------------------------------------
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
l1 = reverseList(l1);
l2 = reverseList(l2);
ListNode l3 = mergeList(l1, l2);
return reverseList(l3);
}
private ListNode reverseList(ListNode curr) {
ListNode prev = null;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
private ListNode mergeList(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(-1);
ListNode curr = dummy;
int carry = 0;
while (l1 != null || l2 != null) {
int sum = carry;
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if (l2 != null) {
sum += l2.val;
l2 = l2.next;
}
curr.next = new ListNode(sum % 10);
curr = curr.next;
carry = sum > 9 ? 1 : 0;
}
if (carry != 0) {
curr.next = new ListNode(1);
}
return dummy.next;
}
}
--------------------------------------------------
--
https://i.imgur.com/bFRiqA3.jpg
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.75.86 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1689561757.A.2C3.html
