445. Add Two Numbers II 兩個數字相加2
阿新 • • 發佈:2018-02-13
兩個 mono ria most new bsp mod arr inpu
來自為知筆記(Wiz)
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 8 -> 0 -> 7
1234567891011121314151617181920212223242526272829303132333435363738394041 | # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers( self , l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ def list2arr(root): res = [] while root: res.append(root.val) root = root. next return res arr1, arr2 = list2arr(l1), list2arr(l2) index1, index2 = len (arr1) - 1 , len (arr2) - 1 carry = 0 root = None while index1 > = 0 or index2 > = 0 or carry: v1, v2 = 0 , 0 if index1 > = 0 : v1 = arr1[index1] index1 - = 1 if index2 > = 0 : v2 = arr2[index2] index2 - = 1 val = (v1 + v2 + carry) carry = 1 if val > = 10 else 0 newNode = ListNode(val % 10 ) newNode. next = root root = newNode return root |
來自為知筆記(Wiz)
445. Add Two Numbers II 兩個數字相加2