6

#yyds干货盘点# LeetCode 热题 HOT 100:两数相加

 2 years ago
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.
neoserver,ios ssh client

#yyds干货盘点# LeetCode 热题 HOT 100:两数相加

精选 原创

灰太狼_cxh 2022-09-08 14:31:12 博主文章分类:leetcode ©著作权

文章标签 链表 代码实现 逆序 文章分类 Java 编程语言 阅读数251

给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。

请你将两个数相加,并以相同形式返回一个表示和的链表。

你可以假设除了数字 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;
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK