LeetCode 2. Add Two Numbers

12人阅读 评论(0) 收藏 举报
分类:

题目

这里写图片描述

思路

用一个数表示进位。

代码

# 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
        """
        addNum = 0
        head = ListNode(0)
        p = head
        while l1 or l2:
            if l1 and l2:
                sumNum = l1.val + l2.val + addNum
            elif l1:
                sumNum = l1.val + addNum
            elif l2:
                sumNum = l2.val + addNum
            tmpNode = ListNode(sumNum)
            if sumNum >= 10:
                sumNum -= 10
                addNum = 1
                tmpNode.val = sumNum
            else:
                addNum = 0
            p.next = tmpNode
            p = p.next
            if l1:
                l1 = l1.next
            if l2:
                l2 = l2.next
        if addNum:
            tmpNode = ListNode(1)
            p.next = tmpNode
        return head.next

查看评论

【Python】第三周 Python Web开发基础(上)

-
  • 1970年01月01日 08:00

【LeetCode】2. Add Two Numbers 解题报告

转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51820937Subject 出处:https://leetcode.com/pro...
  • crazy1235
  • crazy1235
  • 2016-10-24 19:46:34
  • 3780

[C语言][LeetCode][2]Add Two Numbers

[C语言][LeetCode][2]Add Two Numbers
  • Timsley
  • Timsley
  • 2016-04-14 21:25:50
  • 943

[LeetCode][2]Add Two Numbers解析 -Java实现

Q: You are given two linked lists representing two non-negative numbers. The digits are stored in re...
  • u014629433
  • u014629433
  • 2016-06-01 16:34:44
  • 2186

leetcode 2. Add Two Numbers C语言实现

leetcode 2. Add Two Numbers Description You are given two non-empty linked lists represent...
  • banana1006034246
  • banana1006034246
  • 2017-03-31 19:48:34
  • 1261

LeetCode Add Two Numbers 之JavaScript 多种解法

LeetCode Add Two Numbers 之JavaScript 多种解法
  • weixin_36751895
  • weixin_36751895
  • 2017-07-13 12:45:21
  • 509

【python】【leetcode】【算法题目2—Add Two Numbers】

一、题目描述 题目原文:  You are given two linked lists representing two non-negative numbers. ...
  • u014615155
  • u014615155
  • 2016-11-21 12:05:45
  • 2355

[LeetCode#2][C]Add Two Numbers

题目如下: 思路: 其实就是基本的链表操作,只要注意进位的判断就好。代码:/** * Definition for singly-linked list. * struct ListNode ...
  • FaaronZheng
  • FaaronZheng
  • 2016-05-01 19:30:16
  • 503

leetcode(二)—— Add Two Numbers(Python/C++)

Add Two Numbers | LeetCode OJ 逻辑是简单的,主要是处理进位,以及两序列长度不一致的情况; Python# 链表结点定义 class ListNode(object):...
  • lanchunhui
  • lanchunhui
  • 2016-04-11 09:48:50
  • 643

[LeetCode]Add Two Numbers解析

将两个链表的值进行相加,并返回一个新的链表,注意两个地方:一是考虑两个链表的长度是否相同,二是考虑相加后的进位问题 /** * Definition for singly-linked list...
  • rudyn
  • rudyn
  • 2016-08-19 14:12:05
  • 435
    个人资料
    持之以恒
    等级:
    访问量: 8万+
    积分: 5728
    排名: 5688