Lcp春季赛

This commit is contained in:
huangge1199@hotmail.com 2021-04-10 19:32:36 +08:00
parent 368e4b4b24
commit 6b56b63591
2 changed files with 111 additions and 0 deletions

View File

@ -0,0 +1,51 @@
//给你两个 非空 链表来代表两个非负整数数字最高位位于链表开始位置它们的每个节点只存储一位数字将这两数相加会返回一个新的链表
//
// 你可以假设除了数字 0 之外这两个数字都不会以零开头
//
//
//
// 进阶
//
// 如果输入链表不能修改该如何处理换句话说你不能对列表中的节点进行翻转
//
//
//
// 示例
//
// 输入(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
//输出7 -> 8 -> 0 -> 7
//
// Related Topics 链表
// 👍 368 👎 0
package leetcode.editor.cn;
import com.code.leet.entiy.ListNode;
//445:两数相加 II
public class AddTwoNumbersIi {
public static void main(String[] args) {
//测试代码
Solution solution = new AddTwoNumbersIi().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) {
return null;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,60 @@
### 解题思路
执行用时2 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗39 MB, 在所有 Java 提交中击败了9.73%的用户
### 代码
```java
/**
* 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 helper = res;
int temp = 0;
int up = 0;
while (l1 != null && l2 != null) {
int sum = l1.val + l2.val + up;
if ( sum > 9) {
temp = sum - 10;
up = 1;
} else {
temp = sum;
up = 0;
}
helper.next = new ListNode(temp);
helper = helper.next;
l1 = l1.next;
l2 = l2.next;
}
ListNode helper2 = l1 == null ? l2 : l1;
while (helper2 != null) {
int sum = helper2.val + up;
if ( sum > 9) {
temp = sum - 10;
up = 1;
} else {
temp = sum;
up = 0;
}
helper.next = new ListNode(temp);
helper = helper.next;
helper2 = helper2.next;
}
if (up == 1) {
helper.next = new ListNode(up);
helper = helper.next;
}
return res.next;
}
}
```