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
- Leetcode 2. Add Two Numbers The Solution of Python and Javascript
- [Leetcode] 2. Add Two Numbers QuestionEditorial Solution
- [LeetCode] Add Two Numbers, Solution
- [LeetCode 2] Add Two Numbers Solution
- LeetCode #2 Add Two Numbers Cpp Solution
- 2.Add Two Numbers Leetcode Python
- [Leetcode]2.Add Two Numbers @python
- LeetCode 2. Add Two Numbers python 解法
- [leetcode:python] 2.Add Two Numbers
- leetcode 2. Add Two Numbers python
- [leetcode]-add two numbers @python
- 【Leetcode】【python】Add Two Numbers
- Lootcode 1. Two Sum The Solution of Python and Javas
- [LeetCode]371. Sum of Two Integers【&2. Add Two Numbers】
- Leetcode 3. Longest Substring Without Repeating Characters The Solution of Python and Javascript
- leetcode: add two numbers , hash search solution, java. O(n)
- solution about leetcode problem 2 add Two Numbers
- [LeetCode]2.Add Two Numbers
- Java基础之switch语句
- 使用Nexus搭建Maven私服
- 指数运算
- 两个算法--Day3
- Build path entry is missing: org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.
- Leetcode 2. Add Two Numbers The Solution of Python and Javascript
- VS设置代码背景
- Android ViewPager + Fragment懒加载
- MATLAB第二次作业 例1.4-1~2
- 7层网络结构分析
- 人月神话--焦油坑
- socketpair理解
- Lootcode 1. Two Sum The Solution of Python and Javas
- python基础之函数