Leetcode 2. Add Two Numbers The Solution of Python and Javascript
2017-03-19 19:34
627 查看
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:
Javascript:
Python盗用某不知名大神的代码,因为比我的效率高,所以采用这个代码。两种语言思路大部分一致。
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盗用某不知名大神的代码,因为比我的效率高,所以采用这个代码。两种语言思路大部分一致。
相关文章推荐
- Leetcode 3. Longest Substring Without Repeating Characters The Solution of Python and Javascript
- Leetcode 4. Median of Two Sorted Arrays The Solution of Python
- Leetcode 7. Median of Two Sorted Arrays The Solution of Python
- Lootcode 1. Two Sum The Solution of Python and Javas
- [LeetCode 2] Add Two Numbers Solution
- Leetcode 解题 Add Two Numbers Python
- Get the content of an Iframe in Javascript – crossbrowser solution for both IE and Firefox
- Exchange the numbers of row and array of a two-dimensional array, and form a new two-dimensional ar
- LeetCode 2. Add Two Numbers (C++/python/js实现)
- [LeetCode][JavaScript]Add Two Numbers
- leetcode add two numbers python
- Get the content of an Iframe in Javascript – crossbrowser solution for both IE and Firefox
- 2.Add Two Numbers Leetcode Python
- Leetcode 2. Add Two Numbers(python)
- LeetCode #2 Add Two Numbers Cpp Solution
- solution about leetcode problem 2 add Two Numbers
- [leetcode]Add Two Numbers @ Python
- Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers
- leetcode 【 Add Two Numbers 】 python 实现
- [LeetCode]题解(python):002-Add Two Numbers