python输入两个数求和笔试题_02.leetcode题目讲解(Python):两数相加

题目:

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

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

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)

输出:7 -> 0 -> 8

原因:342 + 465 = 807

答案的思路是通过初等数学中的借位来进行计算,我的思路是先获取 l1, l2 的确切数值,通过位数(个十百千万)来进行计算。我的算法复杂度为 O(m + n)其中 m 和 n 为 l1, l2 的位数。比起答案思路,我的算法复杂度要高一些。

# 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

"""

# n is the node of l1

n = l1

i = 1

num_l1 = 0

# get num of l1

while n:

num_l1 = num_l1 + n.val * i

i = i * 10

n = n.next

# m is the node of l2

m = l2

j = 1

num_l2 = 0

# get num of l2

while m:

num_l2 = num_l2 + m.val * j

j = j * 10

m = m.next

# get the sum of l1 , l2

str_num = str(num_l1 + num_l2)

# reverse str_num

str_num = str_num[::-1]

# turn to list output

list_result = []

for s in str_num:

list_result.append(int(s))

return list_result

返回为链表的版本:

# 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

"""

n = l1

i = 1

num_l1 = 0

# get num of l1

while n:

num_l1 = num_l1 + n.val * i

i = i * 10

n = n.next

m = l2

j = 1

num_l2 = 0

# get num of l2

while m:

num_l2 = num_l2 + m.val * j

j = j * 10

m = m.next

str_num = str(num_l1 + num_l2)

str_num = str_num[::-1]

res = list_result = ListNode(0)

for s in str_num:

list_result.next = ListNode(int(s))

list_result = list_result.next

return res.next

ps:如果您有好的建议,欢迎交流 :-D,也欢迎访问我的个人博客 苔原带:tundrazone.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值