Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

两数之和 #15

Open
Bulandent opened this issue Jan 29, 2021 · 0 comments
Open

两数之和 #15

Bulandent opened this issue Jan 29, 2021 · 0 comments

Comments

@Bulandent
Copy link
Owner

Bulandent commented Jan 29, 2021

难度:中等
来源:2. 两数之和

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

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

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

示例 1:

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

示例 2:

输入:l1 = [0], l2 = [0]
输出:[0]

示例 3:

输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]

 
提示:

每个链表中的节点数在范围 [1, 100] 内
0 <= Node.val <= 9
题目数据保证列表表示的数字不含前导零

思路:

  • 首先取出“+”左右两边两个数的最低位;
  • 其次求出他们的和并作为输出结果的最低位;
  • 考虑优化:我们都知道的第一点是加法运算是有进位的,所以使用 carry 来保存进位的结果;
  • 临界值判断:当两个链表长度不一样的时候,总会有 有值 和 null 相加的情况,所以需要处理下;
  • 用一个额外变量保存头链表,用于返回结果;

题解:

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * 
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {
    let sum = new ListNode('0'), 
        head = sum,
        carry = 0;

    while (carry || l1 || l2) {
        let val1 = l1 ? l1.val : 0
        let val2 = l2 ? l2.val : 0
        let r1 = val1 + val2 + carry
        carry = r1 >= 10 ? 1 : 0
        sum.next = new ListNode(r1 % 10)
        sum = sum.next
        if (l1) l1 = l1.next
        if (l2) l2 = l2.next
    }
    return head.next
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant