Leetcode题解(Python): 2.Add Two Numbers
来源:互联网 发布:微信三级分销拼团源码 编辑:程序博客网 时间:2024/06/01 10:39
【题目】
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
Subscribe to see which companies asked this question
【题解】
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ carry = 0;//用于记录加法进位 tmp1 = l1;//保存起始指针 pre = None;//记录遍历时的前一个节点 //1、计算链表1、2一一对应的节点的值 while (l1 != None) and (l2 != None): sum = l1.val + l2.val + carry; if sum >= 10: l1.val = sum - 10; carry = 1; else: l1.val = sum; carry = 0; pre = l1;//记录节点,方便后续使用 l1 = l1.next; l2 = l2.next; //2、处理链表2比1长的情况 if l2 != None: pre.next = l2;//让链表1最后一个非空节点指向链表2的后续节点 l1 = pre.next;//统一l1指针的位置 //3、处理没有被计算过的节点 while l1 != None: if carry == 1: if l1.val == 9: l1.val = 0; carry = 1; else: l1.val += 1; carry = 0; pre = l1;//记录前一个指针,方便后续使用 l1 = l1.next; /* * 4、运行到这里表示链表已经没有节点没被处理过了, * 但是可能存在最后的运算中有进位的情况, * 这时新增一个链表节点,存储进位值。 * 如[1,9]+[2,1]=[3,0,1] */ if carry == 1: pre.next = ListNode(1); return tmp1;
leetcode上的执行时间是128ms,击败99%+。
水平有限,欢迎指正~
如需转发,请注明出处,thx~
0 0
- Leetcode题解(Python): 2.Add Two Numbers
- LeetCode题解--2. Add Two Numbers
- 2. Add Two Numbers : LeetCode 题解
- LeetCode题解:2. Add Two Numbers
- leetcode 题解 2. Add Two Numbers
- Leetcode题解 - 2. Add Two Numbers
- LeetCode Algorithms 2. Add Two Numbers 题解
- LeetCode 2. Add Two Numbers 题解
- 2. Add Two Numbers LeetCode题解
- leetcode题解-2. Add Two Numbers
- LeetCode 题解(26): Add Two Numbers
- LeetCode题解:Add Two Numbers
- LeetCode题解:Add Two Numbers
- [LeetCode] Add Two Numbers题解
- 2.Add Two Numbers Leetcode Python
- [Leetcode]2.Add Two Numbers @python
- LeetCode 2. Add Two Numbers python 解法
- [leetcode:python] 2.Add Two Numbers
- The first result from the daemon was empty.
- redis 用setbit(bitmap)统计活跃用户
- 文章标题
- 阿里云ECS配置
- JSP和Servlet
- Leetcode题解(Python): 2.Add Two Numbers
- java 使用IO从网络下载图片-
- memcached
- CoreText 实现图文混排
- PHP类中的重要知识点
- tomcat启动正常,但是项目无法访问
- 验证二叉查找树
- jQuery深入之源码解析(三)——构造jQuery对象
- 【Android】Android之命令行安装apk