002. Add Two Numbers
Last updated
Last updated
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
v1. 將所有的判斷式包在同一個 while 中
紀錄一 ListNode 的開始(回傳用)
宣告進位紀錄數字 -> carry
宣告一 while 當 l1, l2, carry 都是 0 時才會停止迴圈
while 終須各自判斷 l1, l2 是否已經到底,避免無效的 .next 呼叫
回傳時要回傳 Answer.next ,才不會將一開始宣告的 0 也回傳
v2. 分開處理 - 98.95%
紀錄一 ListNode 的開始(回傳用)
宣告進位紀錄數字 -> carry
宣告一 while 當 l1 或 l2 沒有值時才便停止迴圈 裡面便不需要再判斷是否會呼叫到無效的 .next
建立一 tmplist ,等於 l1 或 l2 尚有值的
判斷 carry 是否不為零,將其加到 nodelist 中