美文网首页
leetcode #2 Add Two Numbers

leetcode #2 Add Two Numbers

作者: huntriver | 来源:发表于2017-07-04 13:03 被阅读0次

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.
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
  • 题目大意
    用两个非空的链表来表示两个非负整数,计算这两个数字的和并将其结果也用链表存储。注意:存储的数字是反向的,比如说 342 用链表来表示就是 2->4->3.

没有什么难度,就是小学时候学的多位数的加法。

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function (l1, l2) {
    let carry = 0; //carry 用来记录进位
    let head, node; //head 用来记录头指针
    while (l1 || l2 || carry) { //当两个链表没有结束 或者 进位>0 继续循环
        let sum = (l1 ? l1.val : 0) + (l2 ? l2.val : 0) + carry;
        l1 && (l1 = l1.next);
        l2 && (l2 = l2.next);
        carry = parseInt(sum / 10);
        let newNode=new ListNode(sum % 10);
        if (!head){
            head=newNode;
            node=head;
        }
        else
            node =( node.next =newNode);
    }
    return head;
};

相关文章

网友评论

      本文标题:leetcode #2 Add Two Numbers

      本文链接:https://www.haomeiwen.com/subject/nvothxtx.html