原题链接:https://leetcode.com/problems/add-two-numbers/
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.
给出两个非空的链表,代表着2个非负整数。链表的第一个节点是整数的个位,第二个是十位,依次类推,顺序和整数的顺序相反。比如(2 -> 4 -> 3)代表的是整数342
求这2个非负整数的和,并且用同样的方式,使用链表表示出来。
你可以假定,这两个非负整数不会以0开头,除了0之外。
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
2. 解题思路
一共有3种情况:
- 相加不进位 如:12+34 = 46 没有进位情况发生
- 相加进位,但是结果和最大加数的位数相同: 例如 9+21 = 30,30是2位数,21和9中,最大的也是2位数
- 相加进位,但是总位数+1: 例如 99 + 1 = 100 ,新的结果是3位数,但是加数中的最大数99是2位数
首先遍历2个链表,将其中的数取出、求和、然后进位。
在遍历链表的时候,一开始我采用的方法是,只要有一个链表结束了,就退出循环,然后再新开一个循环遍历较长链表剩余的部分。这样做非常不方便,因此参考了LeetCode 题解,其实可以使用
if(l1 != null) l1 = l1.next;
来控制遍历不会超过链表的范围。使用
int n1 = (l1 == null ? 0: l1.val);
保证不会抛出异常。
因此,我就把语句
while(l1 != null && l2 != null)
改成了
while(l1 != null || l2 != null)
于是就方便很多了。
实现代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carrybit = 0;//设置进位
int sumbit = 0;//两个链表对应节点相加的和
ListNode ans = new ListNode(0);
ListNode temp = ans;
while(l1 != null || l2 != null) {
int n1 = (l1 == null ? 0: l1.val);
int n2 = (l2 == null ? 0: l2.val);
sumbit = n1 + n2 + carrybit;
carrybit = sumbit / 10;
sumbit %= 10;
temp.next = new ListNode(sumbit);
temp = temp.next;
if(l1 != null) {
l1 = l1.next;
}
if(l2 != null) {
l2 = l2.next;
}
}
//如果还有进位的数,那就再最后面将这个进位补上
//比如 99 + 9 = 108 ,108的1就是在下面代码中补上的
if(carrybit != 0) {
temp.next = new ListNode(carrybit);
}
return ans.next;
}
}