002. Add Two Numbers

Question 2

https://leetcode.com/problems/add-two-numbers/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 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.

Answer

v1. 將所有的判斷式包在同一個 while 中

  1. 紀錄一 ListNode 的開始(回傳用)

  2. 宣告進位紀錄數字 -> carry

  3. 宣告一 while 當 l1, l2, carry 都是 0 時才會停止迴圈

  4. while 終須各自判斷 l1, l2 是否已經到底,避免無效的 .next 呼叫

  5. 回傳時要回傳 Answer.next ,才不會將一開始宣告的 0 也回傳

v2. 分開處理 - 98.95%

  1. 紀錄一 ListNode 的開始(回傳用)

  2. 宣告進位紀錄數字 -> carry

  3. 宣告一 while 當 l1 或 l2 沒有值時才便停止迴圈 裡面便不需要再判斷是否會呼叫到無效的 .next

  4. 建立一 tmplist ,等於 l1 或 l2 尚有值的

  5. 判斷 carry 是否不為零,將其加到 nodelist 中

Last updated