1.原题目:
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
2.翻译:
给出两个非空链表,每一个链表代表一个非负整数,该整数的数位上的数字分别存放在链表的每个节点中,且数字是逆向存储的,求两个整数的和,并将结果同样按数位逆序存放在新的链表中返回。
3.解答:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// l3用来存储数位上的数字相加后的结果,并形成链表
ListNode l3 = new ListNode(0);
// added表示是否有进位
boolean added = false;
// begin存储l3的最初值,即链表头
ListNode begin = l3;
// 当l1和l2都不空的时候,将对应数位上的数相加,并考虑进位。
while(l1 != null && l2 != null) {
int sum = l1.val + l2.val;
// 如果上一个数位有进位,则此数位值需+1
if (added == true) {
sum = sum + 1;
}
// 如果本数位的和大于9,则取和的个位数作为结果数字本数位的值,并进位。如果本数位的和不大于9,则将和作为结果数字相应数位的值,无需进位
if (sum > 9) {
l3.val = sum % 10;
added = true;
} else {
added = false;
l3.val = sum;
added = false;
}
// 如果l1和l2下一位都不是空的,就新建新的一位数字。这个判断是防止l1和l2下一位都是空的时候,结果数字会多出一位
if (l1.next != null && l2.next != null) {
l3.next = new ListNode(0);
l3 = l3.next;
}
l1 = l1.next;
l2 = l2.next;
}
// 处理l1接下来的数位不空,但l2接下来没有数位的情况,循环判断是否需要进位,复制各个数位结果到新的链表中
while (l1 != null) {
if(added == true) {
l1.val = l1.val + 1;
if(l1.val > 9) {
l1.val = 0;
} else{
added = false;
}
}
l3.next = new ListNode(l1.val);
l3 = l3.next;
l1 = l1.next;
}
// 处理l2接下来的数位不空,但l1接下来没有数位的情况,循环判断是否需要进位,复制各个数位结果到新的链表中
while (l2 != null) {
if(added == true) {
l2.val = l2.val + 1;
if(l2.val > 9) {
l2.val = 0;
} else{
added = false;
}
}
l3.next = new ListNode(l2.val);
l3 = l3.next;
l2 = l2.next;
}
// 如果最后一个数位仍有进位,则新建一个数位,值为1
if (added == true) {
l3.next = new ListNode(1);
}
return begin;
}
}