2. Add Two Numbers

Posted 谦曰盛

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2. Add Two Numbers相关的知识,希望对你有一定的参考价值。

Description:

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.

给定两个非空链表(里面的数字可以是0),数字是逆序(非大小关系,即自然数相加减要从各位开始算)排放,最后输出正确顺序的结果

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

Solutions:

 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 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         carry = 0
11         root = n = ListNode(0)
12         while l1 or l2 or carry:
13             v1 = v2 = 0
14             if l1: 
15                 v1 = l1.val 
16                 l1 = l1.next # 依次往后
17             if l2:
18                 v2 = l2.val
19                 l2 = l2.next
20             carry, val = divmod(v1+v2+carry, 10)
21             n.next = ListNode(val)
22             n = n.next
23         return root.next

 

Python 内置函数 divmod() 函数

python divmod() 函数把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b)。

>>>divmod(7, 2)
(3, 1)

  

以上是关于2. Add Two Numbers的主要内容,如果未能解决你的问题,请参考以下文章

Add Two Numbers

2. Add Two Numbers

2_Add Two Numbers --LeetCode

Leetcode 2. Add Two Numbers

Leetcode 2. Add Two Numbers

我的LC之路-2. Add Two Numbers