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;
};