码迷,mamicode.com
首页 > Web开发 > 详细

[leetcode]Add Two Numbers——JS实现

时间:2015-12-15 00:52:10      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:

Javascript的结构体应用,如下:
    function station(name, latitude, longitude){
        this.name = name;
        this.latitude = latitude;
        this.longitude = longitude;
    }
    var s1 = new station(‘station1‘, 100, 200);
    console.log(s1.name+" ‘s latitude :" + s1.latitude );

/**
 * 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 head = new ListNode(0);
    var temp1 = 0;
    var temp2 = 0;
    var val1;
    var val2;
    while(l1 || l2 || temp1) {
        if (l1)val1 = l1.val;
        else val1 = 0;
        if (l2) val2 = l2.val;
        else val2 = 0;
        temp2 = Math.floor((val1 + val2 + temp1) % 10);
        temp1 = Math.floor((val1 + val2 + temp1) / 10);
        head.val += 1; 
        var newNode = new ListNode(temp2);  
        if(head.next == null){  
            head.next = newNode;  
        }
        else {
            var tempNode = head.next;  
            while(tempNode.next != null)  
                tempNode = tempNode.next;  
            tempNode.next = newNode;  
        }
        if (l1)l1 = l1.next;
        if (l2)l2 = l2.next;
    }
    return head.next;
};

 

[leetcode]Add Two Numbers——JS实现

标签:

原文地址:http://www.cnblogs.com/cheermyang/p/5046777.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!