1. 题目原址
https://leetcode.com/problems/add-two-numbers/
2. 题目描述
3. 题目大意
给定两个链表,将链表的对应元素相加,每一位只能存储一个0-9的数,进位向后面进位,然后返回。
4. 解题思路
- 通过while进行循环,定义一个中间的大于10的变量作为进位变量,进位变量的进位放到后面。lSum 哟过来存储中间变量
5. AC代码
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode lSum = null;
ListNode lReturn = null;
int carry = 0;
while (l1 != null && l2 != null) {
// There is something to add
int sum = l1.val + l2.val + carry;
int remain = sum % 10;
carry = sum / 10;
ListNode currNode = new ListNode(remain);
if (lSum != null) {
lSum.next = currNode;
} else {
lReturn = currNode;
}
lSum = currNode;
l1 = l1.next;
l2 = l2.next;
}
ListNode remaining = l1 == null ? l2 : l1; // 存储长的链表
if (lSum == null) { // 这说明有一个链表本身就是空链表
return remaining;
}
lSum.next = remaining;
ListNode remainPrevious = lSum;
while (carry != 0 && remaining != null) { // 两个链表的长度不同且还存在进位。
int sum = remaining.val + carry;
carry = sum / 10;
remaining.val = sum % 10;
remainPrevious = remaining;
remaining = remaining.next;
}
if (carry != 0) { // 到这里说明还需要新new一个节点用来存储多出来的进位元素。
if (remaining == null) {
remainPrevious.next = new ListNode(carry);
} else {
remaining.next = new ListNode(carry);
}
}
return lReturn;
}
}
6. 相似题型
【1】989. Add to Array-Form of Integer 解题原址:https://blog.csdn.net/xiaojie_570/article/details/91829848
【2】 66. Plus One 题目原址:https://leetcode.com/problems/plus-one/
【3】 67. Add Binary 题目原址:https://leetcode.com/problems/add-binary/
【4】 415. Add Strings 题目原址:https://leetcode.com/problems/add-strings/