javascript初探LeetCode之2.Add Two N

作者: ThereThere_0d70 | 来源:发表于2017-07-12 10:08 被阅读245次

    题目

    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.

    example

    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 0 -> 8

    分析

    这是leetcode上的第2题,难度为medium,就是实现两个ListNode结构(题目在代码中已给出)的链表的加法。

    js实现

    /*
     * 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) {
        var carry = 0;//carry存放进位
        var result = new ListNode(),temp = new ListNode();
        result.next = temp;//主要是想用result记录结果链表的表头
        var v1 = l1,v2 = l2;
        while(v1||v2){
            var sum = (v1?v1.val:0)+(v2?v2.val:0)+carry;  
            //v1?v1.val:0是考虑l1和l2可能不等长    
            carry = sum > 9 ? 1 : 0;
            temp.val = sum - carry * 10;//某一位上最终值
            temp.next = (v1?v1.next:null)||(v2?v2.next:null)?(new ListNode()):(carry==1?(new ListNode(1)):null);
            //l1或l2未遍历完,则新建一个ListNode结点;否则检查carry==1判断此时是否有进位,有则也需新建一个ListNode结点,
            //val置1,next置null,以上情况除外,则当前节点temp的next置null
            temp = temp.next?temp.next:null;
            //temp向后移动
            v1 = v1?(v1.next?v1.next:null):null;
            //v1存在且v1.next存在,就继续遍历,否则置null,下面v2类似,双重判断也是考虑考虑l1和l2可能不等长
            v2 = v2?(v2.next?v2.next:null):null;
        };
        return result.next;
    };
    

    总结

    这一题思路简单,但是要注意题目中ListNode的结构,我的做法判断容易理解,但是判断较多,有更优解欢迎交流~

    相关文章

      网友评论

        本文标题:javascript初探LeetCode之2.Add Two N

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