Leetcode 2 Add Two Numbers 题解分析
又 roll 到了一个以前做过的题,不过现在用 Java 也来写一下,是 easy 级别的,所以就简单说下
简要介绍
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 contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
就是给了两个链表,用来表示两个非负的整数,在链表中倒序放着,每个节点包含一位的数字,把他们加起来以后也按照原来的链表结构输出
样例
example 1
1 | Input: l1 = [2,4,3], l2 = [5,6,4] |
example 2
1 | Input: l1 = [0], l2 = [0] |
example 3
1 | Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] |
题解
1 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { |
这里唯二需要注意的就是两个点,一个是循环条件需要包含进位值还存在的情况,还有一个是最后一个节点,如果是空的了,就不要在 new 一个出来了,写的比较挫