当前位置:网站首页>每日一题-两数相加-0711
每日一题-两数相加-0711
2022-08-05 05:17:00 【菜鸡程序媛】
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
解题思路:通过相加两个节点值的和,不断往后走,得到最终的值。需要注意的是,要判断temp是否不等于0,不等于0的时候要继续创建新的节点。
/** * 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) {
if(l1 == null && l2 == null)
return null;
if(l1 == null)
return l2;
if(l2 == null)
return l1;
ListNode head = new ListNode(-1);
ListNode res = head;
int temp = 0;
while(l1 != null || l2 != null){
int val1 = l1 != null ? l1.val : 0;
int val2 = l2 != null ? l2.val : 0;
int sum = val1 + val2 + temp;
res.next = new ListNode(sum % 10);
res = res.next;
temp = sum / 10;
if(l1 != null)
l1 = l1.next;
if(l2 != null)
l2 = l2.next;
}
// 这里要判断一下 否则会漏掉后面的节点
if(temp != 0)
res.next = new ListNode(temp);
return head.next;
}
}
边栏推荐
猜你喜欢

6k+ star,面向小白的深度学习代码库!一行代码实现所有Attention机制!

读论文- pix2pix

OSPF故障排除办法

MaskDistill - Semantic segmentation without labeled data

物联网:LoRa无线通信技术
![[Pytorch study notes] 10. How to quickly create your own Dataset dataset object (inherit the Dataset class and override the corresponding method)](/img/71/f82e76085f9d8e6610f6f817e2148f.png)
[Pytorch study notes] 10. How to quickly create your own Dataset dataset object (inherit the Dataset class and override the corresponding method)

沁恒MCU从EVT中提取文件建立MounRiver独立工程

1004 成绩排名 (20 分)

MSRA proposes extreme masking model ExtreMA for learning instances and distributed visual representations

AIDL detailed explanation
随机推荐
关于存储IOPS你必须了解的概念
The University of Göttingen proposed CLIPSeg, a model that can perform three segmentation tasks at the same time
6k+ star,面向小白的深度学习代码库!一行代码实现所有Attention机制!
关于使用QML的MediaPlayer实现视频和音频的播放时遇到的一些坑
Service
「实用」运维新手一定不能错过的17 个技巧
五、请求处理—Rest映射是怎样实现的?
《基于机器视觉测量系统的工业在线检测研究》论文笔记
OSPF故障排除办法
idea 快速日志
基于STM32F407的WIFI通信(使用的是ESP8266模块)
C语言的一些小常识
对象比较
九、响应处理——内容协商底层原理
TinyFlashDB:一种超轻量的可纠错的通用单片机flash存储方案
framebuffer应用编程及文字显示(2)
六、请求处理—获取请求参数系列注解是怎样工作的?
CVPR 2022 | 70% memory savings, 2x faster training
C语言程序死循环问题解析——变量被修改
网络信息安全运营方法论 (中)