LeetCode 2:兩數相加 Add Two Numbers
阿新 • • 發佈:2019-08-18
給出兩個 非空 的連結串列用來表示兩個非負的整數。其中,它們各自的位數是按照 逆序 的方式儲存的,並且它們的每個節點只能儲存 一位 數字。如果,我們將這兩個數相加起來,則會返回一個新的連結串列來表示它們的和。
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.
您可以假設除了數字 0 之外,這兩個數都不會以 0 開頭。
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807
解題思路:
將兩個連結串列遍歷將相同位置節點值累加,其和過十進一,新連結串列相對位置節點值取其和的個位數值。需要考慮到兩個連結串列長度不同時遍歷方式、連結串列遍歷完成時最後一位是否需要進一位。
Java:
class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode head = new ListNode(0);//虛擬頭節點 ListNode cur = head;//指標 int carry = 0;//進位值 while (l1 != null || l2 != null) {//兩個連結串列均為空時停止遍歷 int x = (l1 != null) ? l1.val : 0;//x為l1的值,如果節點為空,值為0 int y = (l2 != null) ? l2.val : 0;//y為l2的值,如果節點為空,值為0 int sum = carry + x + y;//sum為兩節點值之和 carry = sum / 10;//得進位值(1) cur.next = new ListNode(sum % 10);//sum%10 得餘數即 個位數的值 cur = cur.next;//重新整理指標 if (l1 != null) l1 = l1.next;//l1節點不為空繼續重新整理下一個節點 if (l2 != null) l2 = l2.next;//l2節點不為空繼續重新整理下一個節點 } if (carry > 0) {//如果仍然需要進 1 ,則直接新建一個節點 cur.next = new ListNode(carry); } return head.next; } }
Python3:
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode(0)
cur = head
sum = 0
while l1 or l2:
if l1:#l1不為空
sum += l1.val#累計兩節點值的和
l1 = l1.next#重新整理節點
if l2:
sum += l2.val#累計兩節點值的和
l2 = l2.next#重新整理節點
cur.next = ListNode(sum % 10)//重新整理新連結串列
cur = cur.next
sum = sum // 10
if sum != 0:
cur.next = ListNode(sum)
return head.next
歡迎關注公.眾號一起刷題: 愛寫Bug