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

【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 = 0
        while l1 or l2:
            carry += (l1.val if l1 else 0) + (l2.val if l2 else 0 )
            cur.next = ListNode(carry % 10)  # 注意这里
            carry = carry // 10
            
            cur = cur.next 
            if l1: l1 = l1.next 
            if l2: l2 = l2.next

        if 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.kler.cn/news/106970.html

相关文章:

  • leetcode_2558 从数量最多的堆取走礼物
  • OpenGLSurfaceView的使用经验
  • 虚幻中的网络概述一
  • nexus 快速搭建-本地私有仓库 -maven
  • 浅谈数据结构之队列
  • win10安装Tensorflow(2.10-)使用最新cuda(12+),cudnn(8.9+)
  • OpenCV C++ 图像处理实战 ——《缺陷检测》
  • 【vim 学习系列文章 12 -- vimrc 那点事】
  • 05 MIT线性代数-转置,置换,向量空间Transposes, permutations, spaces
  • ant design vue 的getPopupContainer
  • 【Python机器学习】零基础掌握IsolationForest集成学习
  • Oracel增加IP白名单限制
  • uni-app小程序,uview-ui组件样式无法穿透修改的解决办法
  • 尚未解决:use_python()和use_virtualenv()的使用
  • vue3使用ref和reactive
  • uni-app/vue 文字转语音朗读(附小程序语音识别和朗读)uniapp小程序使用文字转语音播报类似支付宝收款播报小程序语音识别和朗读)
  • Python基础入门例程18-NP18 生成数字列表(列表)
  • 【2024秋招】2023-9-16 贝壳后端开发二面
  • 计算机网络重点概念整理-第一章 计算机网络概述【期末复习|考研复习】
  • 走进国产机器人领军品牌华数机器人,共探数字化变革魔力
  • 智慧停车视频解决方案:如何让AI助力停车管理升级?
  • 垃圾收费站
  • 《动手学深度学习 Pytorch版》 10.3 注意力评分函数
  • python实现批量pdf转txt和word
  • CVE-2022-32991靶场复现
  • 竞赛 深度学习实现行人重识别 - python opencv yolo Reid
  • Win10+Ubuntu20.04双系统双硬盘(SSD+HDD)安装与启动
  • 前端使用 printJS 插件打印多页:第一页空白问题解决
  • 数据结构与算法之矩阵: Leetcode 134. 螺旋矩阵 (Typescript版)
  • Spring Boot集成RESTful API