当前位置:网站首页>每日一题-两数相加-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;
}
}
边栏推荐
猜你喜欢

教你如何封装功能组件和页面组件

C语言入门笔记 —— 函数(1)

网管日记:故障网络交换机快速替换方法

八、请求处理之自定义类型参数绑定原理

【shell编程】第二章:条件测试语句

Tensorflow steps on the pit notes and records various errors and solutions

SQL (2) - join window function view

C语言—三子棋的实现

Comparison and summary of Tensorflow2 and Pytorch in terms of basic operations of tensor Tensor

PID详解
随机推荐
[Pytorch study notes] 10. How to quickly create your own Dataset dataset object (inherit the Dataset class and override the corresponding method)
Tensorflow steps on the pit notes and records various errors and solutions
OSPF故障排除办法
UiPath简介
5G中切片网络的核心技术FlexE
对象比较
WCH系列芯片CoreMark跑分
【UiPath2022+C#】UiPath 练习-数据操作
Detailed explanation of BroadCast Receiver (broadcast)
三、自动配置源码分析
[Pytorch study notes] 9. How to evaluate the classification results of the classifier - using confusion matrix, F1-score, ROC curve, PR curve, etc. (taking Softmax binary classification as an example)
八、请求处理之自定义类型参数绑定原理
六步搞定子网划分
【Multisim仿真】直流稳压电源设计报告
【ts】typescript高阶:键值类型及type与interface区别
CVPR2020 - 自校准卷积
Machine Learning (1) - Machine Learning Fundamentals
【ts】typescript高阶:条件类型与infer
LeetCode刷题之第23题
《基于机器视觉测量系统的工业在线检测研究》论文笔记