第三十一天2019-01-31

leetCode

今天想到了Leetcode的题目,又捡起来做了一道题目。可能比较简单,就当是回忆的题目吧,以后捡起来题目都比较方便。慢慢来吧。坚持下去也好。也不是宁缺毋滥这种借口,是不存在的,还是得每天坚持写点日记,这样以后就能够进行阶段性总结,也可以看以前的东西,希望养成习惯。


Add Two Numbers

*
* [2] Add Two Numbers
*
* https://leetcode.com/problems/add-two-numbers/description/
*
* algorithms
* Medium (30.32%)
* Total Accepted: 733.3K
* Total Submissions: 2.4M
* Testcase Example: '[2,4,3]\n[5,6,4]'
*
* 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
* Explanation: 342 + 465 = 807.
*
*
*/

题目框架

**
* 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 addTwoNumbers = function(l1, l2) {
/**
* 方法一
*/
let List = new ListNode(0)
let head = List
let sum = 0
let carray = 0
while (l1 !== null || l2 !== null || sum > 0) {
if (l1 !== null) {
sum = sum + l1.val
l1 = l1.next
}
if (l2 !== null) {
sum = sum + l2.val
l2 = l2.next
}
if (sum >= 10) {
carray = 1
sum = sum - 10
}
head.next = new ListNode(sum)
head = head.next
sum = carray
carray = 0
}
return List.next
/**
* 方法二
*/
// let node = null
// const carray = arguments[2]
// if (l1 || l2) {
// // 加上进位
// const val1 = l1 ? l1.val1 : 0
// const val2 = l2 ? l2.val2 : 0
// const next1 = l1 ? l1.next : null
// const next2 = l2 ? l2.next : null
// const val = carry ? val1 + val2 + 1 : val1 + val2
// node = new ListNode(val % 10)
// node.next = addTwoNumbers(next1, next2, val >= 10)
// } else if (carray) {
// node = new ListNode(1)
// node.next = null
// }
// return node
};

–end–

文章作者: lmislm
文章链接: http://lmislm.com/2019/01/31/2019-01-31/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 LMISLMのBlog