Fifth. LeetCode 2:Add Two Numbers 兩數之和

WX雲飛發表於2020-11-30

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.

Example 1:

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.

感覺這種思維方式真的很妙。通過一個carry來得到進位數,通過一個sum來算和。

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode prehead = new ListNode(-1);  // 建立一個哨兵節點
        ListNode head = prehead;  // 建立一個指標
        int carry = 0;  // 儲存進位數

        while(l1 != null || l2 != null){  // 只有兩個連結串列都為空的時候才會結束迴圈
            int x = l1 == null ? 0 : l1.val;  // 如果本連結串列已經為空了,就返回0,否則返回當前節點的值
            int y = l2 == null ? 0 : l2.val;  

            int sum = x + y + carry;  // 計算一下當前x + y的值,再加上進位值.
            carry = sum / 10;  // 計算一下當前的進位值

            head.next = new ListNode( sum % 10 );  // 指向下一個節點為sum % 10.  如果 sum > 9,則為個位數,如果sum <= 9,則還是sum
            head = head.next;  // 維護指標
			// if連結串列不為空才會維護指標(防止空指標異常)
            if(l1 != null)
                l1 = l1.next;
            if(l2 != null)
                l2 = l2.next;
        }
		// 出於對最後一位的考慮,如果最後carry為1的話,說明兩個連結串列的最後一位相加>9,這個時候就需要在連結串列的後面再加一位.
        if(carry == 1){
            head.next = new ListNode(carry);
        }

        return prehead.next;

    }
}

相關文章