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

一、题目描述

题目原文:

 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

举例:

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

注意:最终结果要用链表结构表示,返回指向首节点的对象(Python中一切皆对象)。

 

二、题目分析

 我想到的思路比较直接:先把俩个数字用列表表示出来,再转化为整型后进行相加,最后构造相加结果的单链表返回即可。

三、Python代码

#题目中定义的单链表类的结构如下:
#class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        l1,l2为输入的待加和的两个串
        """
        
        #将两个单链表串按位扫到列表listnum1和listnum2中
        listnum1 = []
        listnum2 = []
        while l1 != None:
            listnum1.append(l1.val)
            l1 = l1.next
        while l2 != None:
            listnum2.append(l2.val)
            l2 = l2.next
        
        #将两个数用整型num1和num2表示出来(**运算为指数运算,eg. 2 ** 3 结果为8)
        num1 = 0
        num2 = 0
        for i in range(len(listnum1)):
            num1 = listnum1[i] * (10 ** i) + num1
        for j in range(len(listnum2)):
            num2 = listnum2[j] * (10 ** j) + num2
            
        #计算结果后,构造结果的单链表结构l3
        result = num1 + num2
        l3 = ListNode(0)
        p = ListNode(0)
        p = l3
        #l3和p指向首节点,构造过程中l3不动,仍指向首节点,p进行构造移动
        while result >= 10:
            temp = ListNode(None)
            p.val = result % 10
            p.next = temp
            p = temp
            result = result / 10
        #由于循环到最后一个节点时不再构造新节点,于是退出循环,并给最后一个节点赋值
        p.val = result % 10
        return l3

 

 

四、其他

题目链接:https://leetcode.com/problems/add-two-numbers/

Runtime: 128ms

想法不够优化,欢迎大家留言交流~

 

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值