

#yyds干货盘点# LeetCode 热题 HOT 100:两数相加
source link: https://blog.51cto.com/u_13321676/5662152
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

#yyds干货盘点# LeetCode 热题 HOT 100:两数相加
精选 原创给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.
输入:l1 = [0], l2 = [0]
输出:[0]
输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]
代码实现:
* 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) {
ListNode head = new ListNode(-1);
ListNode cur = head;
int count = 0;
while(l1 != null || l2 != null){
int v1 = 0;
if(l1 != null){
v1 = l1.val;
l1 = l1.next;
}
int v2 = 0;
if(l2 != null){
v2 = l2.val;
l2 = l2.next;
}
int sum = v1 + v2 + count;
cur.next = new ListNode(sum % 10);
cur = cur.next;
count = sum / 10;
}
if(count > 0){
cur.next = new ListNode(count);
}
return head.next;
}
}
Recommend
-
4
#yyds干货盘点# LeetCode 热题 HOT 100:两数之和 精选 原创 灰太狼_cxh 2022-09-...
-
4
#yyds干货盘点# LeetCode 热题 HOT 100:四数之和 精选 原创 灰太狼_cxh 2022-09-...
-
9
#yyds干货盘点# LeetCode 热题 HOT 100: 有效的括号 精选 原创 灰太狼_cxh 2022-...
-
7
#yyds干货盘点# LeetCode 热题 HOT 100:括号生成 精选 原创 灰太狼_cxh 2022-09-...
-
5
#yyds干货盘点# LeetCode 热题 HOT 100:接雨水 精选 原创 灰太狼_cxh 2022-09-27...
-
5
#yyds干货盘点# LeetCode 热题 HOT 100:全排列 精选 原创 灰太狼_cxh 2022-09-27...
-
8
#yyds干货盘点# LeetCode 热题 HOT 100:最大子数组和 精选 原创 灰太狼_cxh 2022...
-
5
#yyds干货盘点# LeetCode 热题 HOT 100:跳跃游戏 精选 原创 灰太狼_cxh 2022-09-...
-
3
#yyds干货盘点# LeetCode 热题 HOT 100:爬楼梯 精选 原创 灰太狼_cxh 2022-10-08...
-
5
#yyds干货盘点# LeetCode 热题 HOT 100:子集 精选 原创 灰太狼_cxh 2022-10-12 1...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK