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

【LeetCode】2. 两数相加

题目链接


在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

Python3

方法: 模拟 ⟮ O ( n ) 、 O ( 1 ) ⟯ \lgroup O(n)、O(1)\rgroup O(n)O(1)⟯

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:cur = dummy = ListNode(None)carry = 0while l1 or l2:carry += (l1.val if l1 else 0) + (l2.val if l2 else 0 )cur.next = ListNode(carry % 10)  # 注意这里carry = carry // 10cur = cur.next if l1: l1 = l1.next if l2: l2 = l2.nextif carry > 0:  # 处理 最后一个进位cur.next = ListNode(carry) return dummy.next 

在这里插入图片描述

C++

/*** Definition for singly-linked list.* struct ListNode {*     int val;*     ListNode *next;*     ListNode() : val(0), next(nullptr) {}*     ListNode(int x) : val(x), next(nullptr) {}*     ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {ListNode *dummy = new ListNode(0);  // 虚拟结点 定义ListNode* cur = dummy;int carry = 0;while (l1 || l2){int n1 = l1 ? l1->val : 0;int n2 = l2 ? l2->val : 0;int total = n1 + n2 + carry;cur->next = new ListNode(total % 10);carry = total / 10;cur = cur->next;if (l1){l1 = l1->next;}if (l2){l2 = l2->next;}}if (carry > 0){cur->next = new ListNode(carry);}return dummy->next;}
};
http://www.lryc.cn/news/205864.html

相关文章:

  • springBoot与Vue共同搭建webSocket环境
  • 【Python】collections.Counter
  • 【Elasticsearch】es脚本编程使用详解
  • Synchronized 关键字
  • Maven系列第8篇:大型Maven项目,快速按需任意构建
  • 卷积神经网络(CNN)的组成结构以及其优点
  • [③ADRV902x]: Digital Filter Configuration(接收端)
  • 企业安全—DevSecOps概述详情
  • 数据结构与算法(十):动态规划与贪心算法
  • 【C++代码】安排行程,N皇后,解数独--代码随想录
  • SpringCloud Alibaba【二】nacos
  • C++中的fsanitize指令
  • 【AI视野·今日Robot 机器人论文速览 第五十八期】Thu, 19 Oct 2023
  • Java截取(提取)子字符串(substring()),Java分割字符串(split())
  • 从厨房间到股市:家庭主妇的华美转身
  • Oracle 数据库的锁排查方法
  • 混合精度训练原理之float16和float32数据之间的互相转换
  • 网络协议--ICMP:Internet控制报文协议
  • 《红蓝攻防对抗实战》三.内网探测协议出网之HTTP/HTTPS协议探测出网
  • 【Win11】系统重装教程(最新最详细)
  • 如何构建一个外卖微信小程序
  • 小知识(5) el-table行样式失效问题
  • 【Docker】Docker数据的存储
  • hive字段关键字问题处理
  • 指定顺序输出
  • (Java)中的数据类型和变量
  • SHELL脚本编程基础,bilibili王晓春老师课程个人笔记(写比较简单,仅供参考)
  • VS code运行vue项目
  • matlab中narginchk函数用法及其举例
  • k8s集群镜像下载加gradana监控加elk日志收集加devops加秒杀项目