第2题:Add Two Numbers
来源:互联网 发布:淘宝卖家哪个商品好用 编辑:程序博客网 时间:2024/05/23 01:15
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
题目要求:给出两个单链表,依次对节点求和,若有进位则加入下一节点。
编程语言:javascript
解法:算法复杂度:O(n) 思路:用一个新的单链表,其浅拷贝接收结果。
/** * 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 ListNode_result = new ListNode(sum % 10);//单节点和
var sum = l1.val + l2.val;
//进位
var carry = sum>=10? 1:0;
l1 = l1.next; l2 = l2.next;
//结果单链表的浅拷贝
var ListNode_current = ListNode_result; while(l1 !== null || l2!== null) { var value1 = l1===null? 0:l1.val; var value2 = l2===null? 0:l2.val; sum = value1 + value2 +carry; var ListNode_temp = new ListNode(sum % 10); carry = sum>=10? 1:0; ListNode_current.next = ListNode_temp; ListNode_current = ListNode_current.next; if(l1 !== null) { l1 = l1.next; } if(l2 !== null) { l2 = l2.next; } }
//监测最后两个节点相加的结果是否大于10
if(carry > 0) { var ListNode_extra = new ListNode(carry); ListNode_current.next = ListNode_extra; } return ListNode_result;};
0 0
- leetcode第2题-Add Two Numbers
- Leetcode 第2题Add Two Numbers
- Leetcode 第 2 题(Add Two Numbers)
- 【LeetCode】第2题: Add Two Numbers
- 第2题:Add Two Numbers
- LeetCode OJ 第2题 Add Two Numbers 解题报告
- leetcode第2题——**Add Two Numbers
- 【LeetCode】LeetCode——第2题:Add Two Numbers
- leetcode 第4题 Add Two Numbers
- 第13题 Add Two Numbers
- 2 Add Two Numbers
- 2、Add Two Numbers
- 2、Add Two Numbers
- 2 Add Two Numbers
- 2Add Two Numbers
- #2 Add Two Numbers
- 2 - Add Two Numbers
- 2Add Two Numbers
- GDUT1169:Krito的讨伐(树 + 优先队列)
- JAVA四则运算字符串解释器
- 列表标签:无序列表、有序列表、定义列表
- C++中cout位数控制
- C++第三次作业(个人所得税计算器、某月有多少天、计算一个分段函数的值)
- 第2题:Add Two Numbers
- [Selenium With C#基础教程] Lesson-06 单选按钮
- Graphics_Work笔记
- bind函数源码解析
- MySQL数据类型
- 史上最简单的UIScrollView+Autolayout出坑指南
- 从运维角度浅谈MySQL数据库优化
- 蓝桥杯BASIC-2——基础练习 01字串
- 双均线策略