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

解题思路:1、考虑到其中一个输入为空的情况

     2、把每个你逆序数计算出它的真实值,相加为num;

       3、直接使用str(num)转化成字符串进行操作。

不得不感叹python处理的简单,现在还仅仅是只窥的冰山一角,就已被惊艳到,嘿嘿

 

 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==None):
11             return l1
12         if(l2==None):
13             return l1
14         
15         l=ListNode(0)
16         tmp1=[l1.val]
17         tmp2=[l2.val]
18         num1=0
19         num2=0
20         while(l1.next!=None):
21             l1=l1.next
22             tmp1.append(l1.val)
23 
24         for i in xrange(len(tmp1)):
25             num1=tmp1[i]*(10**i)+num1
26                 
27         while(l2.next!=None):
28             l2=l2.next
29             tmp2.append(l2.val)
30                 
31         for i in xrange(len(tmp2)):
32             num2=tmp2[i]*(10**i)+num2
33                 
34         num=num1+num2
35         num_str=str(num)
36             
37         for i in xrange(len(num_str)):
38             if(i==0):
39                 l.val=num_str[i]
40                 l.next=None
41             else:
42                 l_tmp=ListNode(0)
43                 l_tmp.val=num_str[i]
44                 l_tmp.next=l
45                 l=l_tmp
46         return l

 

转载于:https://www.cnblogs.com/echo-lsh/p/3988393.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值