当前位置: 首页 > news >正文

【反转链表】力扣 445. 两数相加 II

一、题目

在这里插入图片描述

二、思路

  • 加法运算是从低位开始,向高位进位,因此需要将两个链表进行反转,再进行对齐后的相加操作。
  • 力扣 2. 两数相加

三、题解

/*** 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 ans;l1 = reverseList(l1);l2 = reverseList(l2);return reverseList(addTwo(l1, l2, 0));}// 反转链表public ListNode reverseList(ListNode head) {ListNode pre = null, cur = head;while (cur != null) {ListNode tmp = cur.next;cur.next = pre;pre = cur;cur = tmp;}return pre;}// 求解两数之和 public ListNode addTwo(ListNode l1, ListNode l2, int carry) {// 递归出口if (l1 == null && l2 == null) {return carry != 0 ? new ListNode(carry) : null;}// 确保 l1 是较长的if (l1 == null) {l1 = l2;l2 = null;}int sum = l1.val + (l2 != null ? l2.val : 0) + carry;l1.val = sum % 10;l1.next = addTwo(l1.next, l2 != null ? l2.next : null, sum / 10);return l1;}
}
http://www.lryc.cn/news/494234.html

相关文章:

  • SpringBoot 项目中使用 spring-boot-starter-amqp 依赖实现 RabbitMQ
  • Uniapp 安装安卓、IOS模拟器并调试
  • JavaScript 中的原型和原型链
  • 数组变换(两倍)
  • GBN协议、SR协议
  • 三维扫描检测仪3d扫描测量尺寸-自动蓝光测量
  • 大模型翻译能力评测
  • MySQL隐式转换造成索引失效
  • SuperMap Objects组件式GIS开发技术浅析
  • 多组数输入a+b:JAVA
  • R语言结构方程模型(SEM)在生态学领域中的应用
  • 架构-微服务-服务调用Dubbo
  • 【SpringBoot问题】IDEA中用Service窗口展示所有服务及端口的办法
  • OpenCV 图像轮廓查找与绘制全攻略:从函数使用到实战应用详解
  • 电机驱动MCU介绍
  • 人工智能学习框架详解及代码使用案例
  • 修改Textview中第一个字的字体,避免某些机型人民币¥不显示
  • 彻底理解quadtree四叉树、Octree八叉树 —— 点云的空间划分的标准做法
  • Python时间序列优化之道滑动与累积窗口的应用技巧
  • Buffered 和 BuffWrite
  • 【娱乐项目】基于cnchar库与JavaScript的汉字查询工具
  • 泷羽sec-蓝队基础之网络七层杀伤链 (下)学习笔记
  • FPGA 开发工程师
  • 【Leetcode 每日一题】3250. 单调数组对的数目 I
  • 较类中的方法和属性比较
  • nVisual可视化资源管理工具
  • 自动类型推导(auto 和 decltype)
  • 新型大语言模型的预训练与后训练范式,谷歌的Gemma 2语言模型
  • 基于投影寻踪博弈论-云模型的滑坡风险评价
  • WRF-Chem模式安装、环境配置、原理、调试、运行方法;数据准备及相关参数设置方法