zoukankan      html  css  js  c++  java
  • leetcode 2.两数相加

    给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。

    你可以假设除了数字 0 之外,这两个数字都不会以零开头。

     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     def addTwoNumbers(self, l1, l2):
     9         """
    10         :type l1: ListNode
    11         :type l2: ListNode
    12         :rtype: ListNode
    13         """
    14         if l1 == None:
    15             return l2
    16         if l2 == None:
    17             return l1
    18         len1 = 0
    19         len2 = 0
    20         head = l1
    21         while head!=None:
    22             len1 +=1
    23             head = head.next
    24             
    25         head = l2
    26         while head!= None:
    27             len2 +=1
    28             head = head.next
    29             
    30         if len1 > len2:
    31             shorter = len2
    32             longer = len1
    33         else:
    34             shorter = len1
    35             longer = len2
    36             
    37         carry = 0
    38         sum = None
    39         while shorter != None:
    40             value = longer.val + shorter.val + carry
    41             carry = value / 10
    42             value -= carry * 10
    43             if sum = 0:
    44                 sum = ListNode(value)
    45                 result = sum
    46             else:
    47                 sum.next = ListNode(value)
    48                 sum = sum.next
    49                 
    50             longer = longer.next
    51             shorter = shorter.next
    52             
    53         while longer != None:
    54             value = longer.val + carry
    55             carry = value / 10
    56             value -= carry * 10
    57             
    58             sum.next = ListNode(value)
    59             sum = sum.next
    60             
    61             longer = longer.next
    62             
    63         if carry != 0:
    64             sum.next = ListNode(carry)
    65             
    66         return result
    67         
    68 
    69         
    70         
  • 相关阅读:
    雷锋依然在人间 工厂方法模式
    为别人做嫁衣 代理模式
    穿什么有这么重要? 装饰模式
    437. Path Sum III
    434. Number of Segments in a String
    447. Add Strings
    414. Third Maximum Number
    412. Fizz Buzz
    404. Sum of Left Leaves
    405. Convert a Number to Hexadecimal
  • 原文地址:https://www.cnblogs.com/chengchengaqin/p/9505731.html
Copyright © 2011-2022 走看看