• leetcode 【 Add Two Numbers 】 python 实现


    题目

    You are given two linked lists representing two non-negative numbers. 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.

    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 0 -> 8

    代码:oj测试通过 Runtime: 171 ms

     1 # Definition for singly-linked list.
     2 # class ListNode:
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.next = None
     6 
     7 class Solution:
     8     # @return a ListNode
     9     def addTwoNumbers(self, l1, l2):
    10         if l1 is None:
    11             return l2
    12         if l2 is None:
    13             return l1
    14         
    15         dummyhead = ListNode(0)
    16         p = ListNode(0)
    17         dummyhead.next = p
    18         
    19         jinwei = 0
    20         while l1 is not None and l2 is not None:
    21             curr_total = l1.val + l2.val + jinwei
    22             l1 = l1.next
    23             l2 = l2.next
    24             curr_digit = curr_total % 10
    25             jinwei = curr_total / 10
    26             curr_node = ListNode(curr_digit)
    27             p.next = curr_node
    28             p = p.next
    29             
    30         if l1 is not None:
    31             while l1 is not None:
    32                 curr_total = l1.val + jinwei
    33                 l1 = l1.next
    34                 curr_digit = curr_total % 10
    35                 jinwei = curr_total / 10
    36                 curr_node = ListNode(curr_digit)
    37                 p.next = curr_node
    38                 p = p.next
    39         if l2 is not None:
    40             while l2 is not None:
    41                 curr_total = l2.val + jinwei
    42                 l2 = l2.next
    43                 curr_digit = curr_total % 10
    44                 jinwei = curr_total / 10
    45                 curr_node = ListNode(curr_digit)
    46                 p.next = curr_node
    47                 p = p.next
    48         
    49         if jinwei == 1:
    50             curr_node = ListNode(1)
    51             p.next = curr_node
    52         
    53         return dummyhead.next.next

    思路

    就是加法运算 注意两条链表上所有值计算过后 是否有进位;如果有进位 需要再处理一下。

  • 相关阅读:
    Mac使用pip安装Tensorflow
    php之curl get post curl_multi_exec 请求用法
    重新捡起的知识-字节(Byte)、比特(bit)-计算机常识
    Mac打不开Wireshark dyld: Library not loaded: /usr/X11/lib/libcairo.2.dylib
    ViewController生命周期
    转 try catch finally
    VPS centOS搭建gitlab小结
    UIButton小节
    python 统计单词个数,并按个数与字母排序
    GCP 谷歌云平台申请教程
  • 原文地址:https://www.cnblogs.com/xbf9xbf/p/4228421.html
Copyright © 2020-2023  润新知