LeetCode-Add Two Numbers(JS题解)

Add Two Numbers


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.
Example:
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
Explanation: 342 + 465 = 807.

本题要求将以链表存储的两个整数相加,求和的结果存储在新的链表中,最后返回新的链表。
可以理解为使用两个链表,把两个整数相加。
本题需要注意的是:

1.整数相加需考虑进位;
2.两个链表的长度可能不一样,不一样数值应该为0;
3.进位为0时的情况

输入:(2→4→3)+(5→6→4) 
输出:7 - > 0 - > 8

Javascript:

//Definition for singly-linked list.
 function ListNode(val) {
     const obj={};
     obj.val = val;
     obj.next = null;
     return obj;
 }

/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {
    //只作为头结点
    const head=ListNode(0);
    let p=head;
    let node1=l1,node2=l2,carry=0;
    //如果节点为空进位也为空不执行,考虑到5+5=10的情况
    while(node1||node2||carry){
        const val1=node1?node1.val:0,
              val2=node2?node2.val:0,
              sum=val1+val2+carry;
        const node=ListNode(sum%10);
        carry=parseInt(sum/10);
        p.next=node;
        p=p.next;
        node1=node1?node1.next:node1;
        node2=node2?node2.next:node2;
    }
    return head.next;
};

猜你喜欢

转载自blog.csdn.net/qq_32013641/article/details/86588869
今日推荐