Leetcode刷题-2.两数相加(JS)

题目:

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 contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.

题目大意:给定两个逆序的链表,要求将两个链表相加,返回的结果是结果链表的头结点。

思路:

  1. 首先创建一个新链表dummy,以及一个用来遍历链表的curr指针,一个处理进位变量的carry
  2. 进入while循环统计两数之和
  3. 先通过取模运算,计算sum的值
  4. 检查carry的值(通过Math.floor()计算)
  5. curr指向下一个值
  6. 循环结束后检查carry的值,若不为0则要增加一位

代码:

var addTwoNumbers = function(l1, l2) {
    let dummy = new ListNode(); //结果链表
    let curr = dummy; //遍历链表的指针
    let carry = 0;  //进位标志
    while (l1 != null || l2 != null){ //循环结束条件
       let sum = 0; 
       if(l1 != null){
           sum += l1.val; //加上l1当前位的值
           l1 = l1.next; //指向下一个l1节点
       }
       if(l2 != null){
           sum += l2.val; //加上l2当前位的值
           l2 = l2.next; //指向下一个l2节点
       }
       sum += carry; //加上进位才是当前位的总和
       curr.next = new ListNode(sum%10); //取余得到当前位的结果
       carry = Math.floor(sum/10); //更新进位标志
       curr = curr.next; 
    }
    if(carry != 0){ //最后判断有无进位
        curr.next = new ListNode(carry); //若有进位,则要增加一个节点
    }
    return dummy.next;
};

参考资料:

还是要感谢B站JS老毕,讲的实在太好啦~
https://www.bilibili.com/video/BV1wA411b7qZ?from=search&seid=15127917311607283810

你可能感兴趣的:(leetcode)