原题
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入: (2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 0 -> 8
原因: 342 + 465 = 807
解法
思想
模拟数学规则,将每一位对应的值和进位相加,将null一般化为0。
代码
Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode preHead = new ListNode(0);
int val1,val2,sum = 0;
int carry = 0;
ListNode cur = preHead;
while(l1!=null || l2!=null || carry != 0){
val1 = l1==null?0:l1.val;
val2 = l2==null?0:l2.val;
sum = val1+val2+carry;
if(sum>=10) {
carry = 1;
sum -= 10;
}else carry = 0;
cur.next = new ListNode(sum);
cur = cur.next;
l1 = l1 == null?null:l1.next;
l2 = l2 == null?null:l2.next;
}
return preHead.next;
}
}
Go(2020/07/04)
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
var dummy *ListNode = new(ListNode)
var node *ListNode = dummy
var num1,num2,carry int
for{
if l1 == nil && l2 == nil && carry == 0 { return dummy.Next }
if l1 != nil{
num1, l1 = l1.Val, l1.Next
}else{
num1 = 0
}
if l2 != nil{
num2, l2 = l2.Val, l2.Next
}else{
num2 = 0
}
sum := num1 + num2 + carry
if sum >= 10{
sum,carry = sum - 10 , 1
}else{
carry = 0
}
node.Next = &ListNode{Val:sum}
node= node.Next
}
}
Python(2020/07/04)
(秉承人生苦短原则,Python条件分支尽量都写在了一行,如果不清晰的话请看上面语言的写法)
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy = ListNode(0)
cur = dummy
num1 = num2 = carry = 0
while l1 != None or l2 != None or carry != 0:
if l1 != None: num1, l1 = l1.val, l1.next
else: num1 = 0
if l2 != None: num2, l2 = l2.val, l2.next
else: num2 = 0
sum = num1 + num2 + carry
if sum >= 10:sum,carry = sum - 10 , 1
else: carry = 0
cur.next = ListNode(sum)
cur = cur.next
return dummy.next
原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/leetcode2-%e4%b8%a4%e6%95%b0%e7%9b%b8%e5%8a%a0/