Skip to content

Latest commit

 

History

History
118 lines (101 loc) · 2.59 KB

2.两数相加.md

File metadata and controls

118 lines (101 loc) · 2.59 KB

2.两数相加

url

题目

给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。

请你将两个数相加,并以相同形式返回一个表示和的链表。

你可以假设除了数字 0 之外,这两个数都不会以 0 开头。

lc-addtwonumber1-snb8Qb

输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.
输入:l1 = [0], l2 = [0]
输出:[0]
输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]

方法

code

js

let addTwoNumbers = (l1, l2) => {
    if (l1 === null)
        return l2;
    if (l2 === null)
        return l1;
    let p1 = l1, p2 = l2;
    let l3 = new ListNode(0);
    let p3 = l3, carry = 0;
    while (p1 !== null || p2 !== null) {
        let a = p1 === null ? 0 : p1.val;
        let b = p2 === null ? 0 : p2.val;
        p3.next = new ListNode((a + b + carry) % 10);
        carry = Math.floor((a + b + carry) / 10);
        p1 = p1 === null ? null : p1.next;
        p2 = p2 === null ? null : p2.next;
        p3 = p3.next;
    }
    p3.next = carry === 1 ? new ListNode(1) : null;
    return l3.next;
};

go

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	if l1 == nil {
		return l2
	}
	if l2 == nil {
		return l1
	}
	p1, p2 := l1, l2
	l3 := &ListNode{Val: 0}
	p3 := l3
	carry := 0
	for p1 != nil || p2 != nil {
		a := 0
		b := 0
		if p1 != nil {
			a = p1.Val
			p1 = p1.Next
		}
		if p2 != nil {
			b = p2.Val
			p2 = p2.Next
		}
		p3.Next = &ListNode{Val: (a + b +carry) % 10}
		carry = (a + b + carry) / 10
		p3 = p3.Next
	}
	if carry == 1 {
		p3.Next = &ListNode{Val: 1}
	}
	return l3.Next
}

java

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null)
            return l2;
        if (l2 == null)
            return l1;
        ListNode p1 = l1, p2 = l2;
        ListNode l3 = new ListNode(0);
        ListNode p3 = l3;
        int carry = 0;
        while (p1 != null || p2 != null) {
            int a = p1 == null ? 0 : p1.val;
            int b = p2 == null ? 0 : p2.val;
            p3.next = new ListNode((a + b + carry) % 10);
            carry = (a + b + carry) / 10;
            p1 = p1 == null ? null : p1.next;
            p2 = p2 == null ? null : p2.next;
            p3 = p3.next;
        }
        p3.next = carry == 1 ? new ListNode(1) : null;
        return l3.next;
    }
}