2:两数相加

This commit is contained in:
huangge1199 2021-06-07 10:13:01 +08:00
parent a303c8f73c
commit 4e9c28bb7c
2 changed files with 137 additions and 0 deletions
src/main/java/leetcode/editor/cn

View File

@ -0,0 +1,97 @@
//给你两个 非空 的链表表示两个非负的整数它们每位数字都是按照 逆序 的方式存储的并且每个节点只能存储 一位 数字
//
// 请你将两个数相加并以相同形式返回一个表示和的链表
//
// 你可以假设除了数字 0 之外这两个数都不会以 0 开头
//
//
//
// 示例 1
//
//
//输入l1 = [2,4,3], l2 = [5,6,4]
//输出[7,0,8]
//解释342 + 465 = 807.
//
//
// 示例 2
//
//
//输入l1 = [0], l2 = [0]
//输出[0]
//
//
// 示例 3
//
//
//输入l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
//输出[8,9,9,9,0,0,0,1]
//
//
//
//
// 提示
//
//
// 每个链表中的节点数在范围 [1, 100]
// 0 <= Node.val <= 9
// 题目数据保证列表表示的数字不含前导零
//
// Related Topics 递归 链表 数学
// 👍 6286 👎 0
package leetcode.editor.cn;
import com.code.leet.entiy.ListNode;
//2:两数相加
public class AddTwoNumbers{
public static void main(String[] args) {
//测试代码
Solution solution = new AddTwoNumbers().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int sum = 0;
ListNode temp = l1;
while (temp != null) {
sum = l2 == null ? temp.val + sum : temp.val + l2.val + sum;
temp.val = sum % 10;
sum = sum / 10;
if (l2 != null && temp.next == null && l2.next == null && sum > 0) {
temp.next = new ListNode(sum);
sum = 0;
l2 = null;
} else if (l2 != null && temp.next == null && l2.next != null) {
temp.next = l2.next;
l2 = null;
} else if (l2 != null) {
l2 = l2.next;
} else {
if (temp.next == null && sum > 0) {
temp.next = new ListNode(sum);
sum = 0;
}
l2 = null;
}
temp = temp.next;
}
return l1;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,40 @@
<p>给你两个 <strong>非空</strong> 的链表,表示两个非负的整数。它们每位数字都是按照 <strong>逆序</strong> 的方式存储的,并且每个节点只能存储 <strong>一位</strong> 数字。</p>
<p>请你将两个数相加,并以相同形式返回一个表示和的链表。</p>
<p>你可以假设除了数字 0 之外,这两个数都不会以 0 开头。</p>
<p> </p>
<p><strong>示例 1</strong></p>
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2021/01/02/addtwonumber1.jpg" style="width: 483px; height: 342px;" />
<pre>
<strong>输入:</strong>l1 = [2,4,3], l2 = [5,6,4]
<strong>输出:</strong>[7,0,8]
<strong>解释:</strong>342 + 465 = 807.
</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>l1 = [0], l2 = [0]
<strong>输出:</strong>[0]
</pre>
<p><strong>示例 3</strong></p>
<pre>
<strong>输入:</strong>l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
<strong>输出:</strong>[8,9,9,9,0,0,0,1]
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>每个链表中的节点数在范围 <code>[1, 100]</code></li>
<li><code>0 <= Node.val <= 9</code></li>
<li>题目数据保证列表表示的数字不含前导零</li>
</ul>
<div><div>Related Topics</div><div><li>递归</li><li>链表</li><li>数学</li></div></div>\n<div><li>👍 6286</li><li>👎 0</li></div>