Leetcode 第 02.Add Two Numbers 题,题目难度 Medium。
一. 题目要求
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
Explanation: 342 + 465 = 807.
题目大意
两个整数逆序存放在两个链表中。即链表的每个节点都存储了数字的一位,第一个节点存储的是个位,以此类推。通过这两个链表进行求和。
二. 解题思路 & 代码实现
既然是求和,那么从头遍历两个链表相加就可以了,遍历计算过程中需要注意两个问题:
-
计算时的进位问题,另外遍历结束后如果仍有进位需要新建一个节点存储
-
有一个链表提前遍历完成,则该链表后续遍历时的值都为 0
虽然是 medium 难度的题目,但做起来并不难,把遍历过程中的计算想清楚就可以了。实现代码如下:
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode result = new ListNode(0);
ListNode tail = result;
// 是否进位
int isopsephy = 0;
while (l1 != null || l2 != null) {
int value1 = l1 == null ? 0:l1.val;
int value2 = l2 == null ? 0:l2.val;
int val = value1 + value2 + isopsephy;
if (val > 9) {
val = val % 10;
isopsephy = 1;
}else {
isopsephy = 0;
}
tail.val = val;
l1 = l1 == null? null: l1.next;
l2 = l2 == null? null: l2.next;
// 啷
if (l1 == null && l2 == null) {
if (isopsephy > 0) {
tail.next = new ListNode(isopsephy);
tail = tail.next;
}
break;
}
tail.next = new ListNode(0);
tail = tail.next;
}
return result;
}
}
- 运行结果
Runtime: 1 ms, faster than 100.00% of Java online submissions for Add Two Numbers.
老铁都看到这了来一波点赞、评论、关注三连可好
我是 AhriJ邹同学,前后端、小程序、DevOps 都搞的炸栈工程师。博客持续更新,如果觉得写的不错,欢迎来一波老铁三连,不好的话也欢迎指正,互相学习,共同进步。