【LeetCode】 2. Add Two Numbers 两数相加 (Medium)(JAVA)
题目地址: https://leetcode.com/problems/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
Explanation: 342 + 465 = 807.
题目大意
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
解题方法
两个链表结果相加就行,主要是判断有没有进位,在最后结束的时候还需要判断是否要进位。
有个小技巧,可以先创建一个ListNode res,这样就不需要判断 pre 是否为空了,直接用。
Accepted
/**
* 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) {
ListNode res = new ListNode(0);
ListNode pre = res;
int carry = 0;
while (l1 != null || l2 != null) {
ListNode cur = l1;
if (l1 != null) {
cur = l1;
carry += l1.val;
l1 = l1.next;
}
if (l2 != null) {
cur = l2;
carry += l2.val;
l2 = l2.next;
}
cur.val = carry % 10;
carry /= 10;
pre.next = cur;
pre = cur;
}
if (carry > 0) {
pre.next = new ListNode(carry);
}
return res.next;
}
}
执行用时 内存消耗
2 ms 40.3 MB