Leetcode 2. Add Two Numbers The Solution of Python and Javascript

来源:互联网 发布:打破刚性兑付 知乎 编辑:程序博客网 时间:2024/05/21 14:56

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

Python:

class Solution(object):        def addTwoNumbers(self,l1,l2):        """        :type l1: ListNode        :type l2: ListNode        :rtype: ListNode        """        res=pro=ListNode(0)#定义res和pro,指向相同位置        count=0        while l1 or l2 or count:#判断循环是否继续,即了l1,l2,和进位count有任意存在            if l1:#计算当前位的和,并把l1,l2指向next                count+=l1.val                l1=l1.next            if l2:                count+=l2.val                l2=l2.next            pro.next=ListNode(count%10)#把当前位的值付给pro            pro=pro.next#pro进位            count/=10#计算下一位进位        return res.next#因为指向相同位置,同时pro指向最后一位,因此输出res

Javascript:

/** * 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 l3= new ListNode(0);    var b=0;    while(l1||l2||b){        if(l1){m=l1.val}        else{m=0}        if(l2){n=l2.val}        else{n=0}        a=(m+n+b)%10;        var newNode = new ListNode(a);        b=Math.floor((m+n+b)/10);        if(l3.next == null){              l3.next = newNode;        }        else {            var c = l3.next;              while(c.next != null)                c = c.next;            c.next = newNode;          }        if(l1){l1=l1.next;}        if(l2){l2=l2.next;}    }    return l3.next};

Python盗用某不知名大神的代码,因为比我的效率高,所以采用这个代码。两种语言思路大部分一致。

0 0