2017暑期工程训练day1_leetcode2_Add Two Numbers

LeetCode 2.Add Two Numbers

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

题目描述

给出两个非空链表,分别代表两个非负整数。每一位数被反向存储(即个,十,百...这样的顺序)在每个结点上。将这两个数加起来并把它们的和表示成一个链表.
代码中给出了ListNode的构造函数:
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**

解决方式

思想:遍历两个链表,按照一般加法运算的方式进行对位相加;
需要注意三个点:
1.两个链表并不一定一样长,加法运算的结果一定不比最长的链表短,所以加法运算要进行到长链表的最后一位;
2.考虑加法运算进位,1中的说法是一种一般情况,特殊情况是最后一位加完之后需要进位,这时需要特殊判断;
3.返回值应当是一个链表,所以循环中的每一个.next都要初始化成ListNode.
实现代码如下:
/**
* 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 res = new ListNode((l1.val + l2.val)%10);
var cur = Math.floor((l1.val + l2.val)/10);
var head = res;
var next1 = l1.next, next2 = l2.next;
while(next1 || next2){
var sum = (next1?next1.val:0) + (next2?next2.val:0) + cur;
if(sum < 10){
head.next = new ListNode(sum);
cur = 0;
}
else{
head.next = new ListNode(sum - 10);
cur = 1;
}
head = head.next;
next1 = next1?next1.next:null;
next2 = next2?next2.next:null;
}
if(cur)
head.next = new ListNode(cur);
return res;
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值