# LeetCode 2. Add Two Numbers (Java) ###### tags: `leetcode` `Java` ## Description > 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 contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. >有兩個非空的linked list代表的整數,其中每個節點包含一個數字。數字存儲按照在原來整數中相反的順序。寫出一個函數將兩個整數相加,用linked list形式回傳兩者的合。 ## Example ``` Input: l1 = [2,4,3], l2 = [5,6,4] Output: [7,0,8] Explanation: 342 + 465 = 807. ``` ``` Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] Output: [8,9,9,9,0,0,0,1] ``` ## Idea - 會有進位問題所以設定一個`carry`變數(0->沒有進位,1->有進位) - 並且在計算完一個節點之後`curr`中指向`result`下一個節點在做同樣的計算,`l1` `l2`則判斷是否下一個節點是否NULL也指向下一個節點 - 直到l1和l2都指向連結的最後NULL則程式結束。 ## Code ```java= /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode result = new ListNode(0);//設定新的空鏈結儲存結果 ListNode curr = result; int carry = 0;//進位 while(l1 != null || l2 != null) { int x = (l1!=null) ? l1.val: 0; int y = (l2!=null) ? l2.val: 0; int sum = x + y + carry; if(sum >= 10) carry = 1; else carry = 0; curr.next = new ListNode(sum%10); curr = curr.next; if(l1 != null) l1 = l1.next; if(l2 != null) l2 = l2.next; } //carry = 1 if(carry == 1) curr.next = new ListNode(1); return result.next;//回傳鏈結的第一個節點 } } ```