Leetcode_02 two numbers together [] - [Difficulty: Moderate]

Article Directory:

  • topic
  • A script
  • Script logic analysis

topic:

We are given two non-empty list is used to represent two non-negative integer. Where their respective bits are stored in reverse order of the way, and they each node can store only one digit.

If we add up these two numbers, it will return a new list and to represent them.

You can assume that in addition to the numbers 0, these two numbers will not begin with 0.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Cause: 342 + 465 = 807


A script: [takes 80ms]

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        str1 = ""
        str2 = ""
        first = l1
        second = l2
        while first != None:
            str1 += str(first.val)
            first = first.next
        while second != None:
            str2 += str(second.val)
            second = second.next
        str3 = str1[::-1]
        str4 = str2[::-1]
        n1 = int(str3) + int(str4)
        str5 = str(n1)
        str6 = str5[::-1]
        len1 = len(str6)
        l3 = ListNode(0)
        l3.next = l1
        third = l3
        for i in range(len1):
            bb = ListNode(int(str6[i]))
            third.next = bb
            third = third.next
        l3 = l3.next
        return(l3)

 


 

Script logic analysis:

  1. This question involves knowledge of a single list, in this I do a brief introduction: Features a single list is the current node will record the value of this node, and point to the next node, that property owned by val and the next;
  2. As an example: l1 = 2 -> 4 -> 3 (can not be so assigned, for convenience of presentation only), i.e., l1 is a singly linked list of the third node; if l1 = l1.next then equal to l1 = 4 -> 3; the node movement and assignment are typically performed by the intermediate variable; as: first = l1, l1 and first case the same point to a linked list, first.val = 5 represents a modified value of the current node 5, this modification affects the l1 list, because the first l1 and the same point to a linked list; first = first.next, at this time first = 4 -> 3 [l1 list at this time is also part of the first list, the first modified value is modified value of l1]  
  3. Seen from Title: Title two addends the inverted form of the list becomes the logic script is first reduced and adding two addends, then the sum of two numbers of the string, through the linked list and each of the values ​​given list; then remove excess head node to the list

Guess you like

Origin www.cnblogs.com/mailong/p/12227328.html