[leetcode:python] 2.Add Two Numbers
2017-05-10 11:36
435 查看
题目描述:
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
题意:
给定两个非空链表,存放的是非负整数。数值可逆序存放,每个节点只存放一个数。使两表相加并返回和表。
假设两个表的开头都没有0,除非这个表只包含0
代码:
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
题意:
给定两个非空链表,存放的是非负整数。数值可逆序存放,每个节点只存放一个数。使两表相加并返回和表。
假设两个表的开头都没有0,除非这个表只包含0
代码:
# Definition for singly-linked list. # 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 """ head = l1 carry = 0 while l1 and l2: l1.val += (l2.val+carry) carry = l1.val/10 l1.val = l1.val%10 pre = l1 l1 = l1.next l2 = l2.next if l2: pre.next = l2 l2.val += carry carry = l2.val/10 l2.val = l2.val%10 pre = l2 while carry: if pre.next: pre = pre.next pre.val += carry carry = pre.val/10 pre.val = pre.val%10 else: pre.next = ListNode(carry) carry = 0 return head
相关文章推荐
- 【LeetCode with Python】 Add Two Numbers
- Leetcode 解题 Add Two Numbers Python
- python写算法题:leetcode: 2. Add Two Numbers
- LeetCode 2 — Add Two Numbers(C++ Java Python)
- 【Leetcode】【python】Add Two Numbers
- leetcode 【 Add Two Numbers 】 python 实现
- leetcode python - addTwoNumbers
- Python leetcode #2 Add Two Numbers
- 【LeetCode】【Python】【C++】2. Add Two Numbers代码实现
- [leetcode]Add Two Numbers@python
- Leetcode 2. Add Two Numbers(python)
- leetcode(二)—— Add Two Numbers(Python/C++)
- [LeetCode]4 Add Two Numbers(C++,Python实现)
- leetcode 2. Add Two Numbers python实现的理解,结点,单链表的应用,大数,进位的问题
- [leetcode]Add Two Numbers @ Python
- [LeetCode]题解(python):002-Add Two Numbers
- [Leetcode]2.Add Two Numbers @python
- [Leetcode] Add Two Numbers Python实现 详细讲解
- 【leetcode】2. Add Two Numbers(Python & C++)
- (python)leetcode刷题笔记 02 Add Two Numbers