惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Vercel News
Vercel News
Y
Y Combinator Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
The GitHub Blog
The GitHub Blog
N
Netflix TechBlog - Medium
MyScale Blog
MyScale Blog
F
Fortinet All Blogs
Microsoft Azure Blog
Microsoft Azure Blog
H
Help Net Security
C
Check Point Blog
博客园 - 聂微东
云风的 BLOG
云风的 BLOG
M
MIT News - Artificial intelligence
U
Unit 42
WordPress大学
WordPress大学
B
Blog
Last Week in AI
Last Week in AI
人人都是产品经理
人人都是产品经理
T
Tailwind CSS Blog
D
DataBreaches.Net
G
Google Developers Blog
T
The Blog of Author Tim Ferriss
Hugging Face - Blog
Hugging Face - Blog
IT之家
IT之家

姓王者的博客

Linux用户Secure Boot自主维护指南 | 姓王者的博客 MAD Bugs 已经开始——关于信息安全的军备竞赛 | 姓王者的博客 解决钉钉Dingtalk无法在Linux新版内核上启动问题-修复可执行栈错误 | 姓王者的博客 突发:GitHub 正遭受大规模 Issue 赌博广告轰炸 | 姓王者的博客 Ubuntu26.04-beta体验:坚毅浣熊! | 姓王者的博客 fakeclaw装作龙虾发贴吧 | 姓王者的博客 找回12年前的QQ记忆 | 姓王者的博客 在Linux上玩Flash网页游戏-洛克王国 | 姓王者的博客 Copilot将使用交互数据来训练 | 姓王者的博客 重要通知-请更新我的GPG公钥 | 姓王者的博客 为了自由Android | 姓王者的博客 GPL"2,3"事 | 姓王者的博客 短文-对VitePlus的一点🤏小贡献 | 姓王者的博客 Bing收录没了?亲测有效的快速恢复指南 | 姓王者的博客 解决桌面设备二维码快速识别的工具-ClipQR | 姓王者的博客 解决 Nautilus 自定义终端插件安装依赖问题 | 姓王者的博客 OpenClaw 该熄火了 | 姓王者的博客 Vite8 - 统一的基建开始 | 姓王者的博客 Astro 6 推出啦 | 姓王者的博客 ubuntu的openvpn异常暂停推送更新 | 姓王者的博客 Ubuntu 24.04 安装 Win10 虚拟机 | 姓王者的博客 ESA-后记:热爱阿里云 | 姓王者的博客 Moonbit 0.8.0 重大发布,我也要改一下我的包 | 姓王者的博客 ESA Pages 边缘开发大赛获奖 | 姓王者的博客 Astro: 优化katex,mermaid和灯箱使用 | 姓王者的博客 从edgeone迁移到esa | 姓王者的博客 出租人类:AI时代的荒诞与真实 | 姓王者的博客 Astro 5.17构建性能优化实践:从18s到13s | 姓王者的博客 Moonbit License Checker 开发使用 | 姓王者的博客 Stalux Astro博客主题自荐 | 姓王者的博客
LeetCode:2. 两数相加 | 姓王者的博客
作者:xingwangzhe · 2024-09-22 · via 姓王者的博客

🕒 阅读时间:1 分钟 📝 字数:177 👀 阅读量: Loading...

两数相加

前置声明

LeetCode所有题目版权均归 LeetCode 和 力扣中国 所有

本文仅提题解与思路,详情请访问官网查看


LeetCode Logo

两数相加

O(n)复杂度

按题意来,两个链遍历,取个位,进十位就行了。

/**

* 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 p = new ListNode(0);

ListNode cur = p;

int pp = 0;

while (l1 != null || l2 != null || pp != 0) {

int s1 = l1 != null ? l1.val : 0;

int s2 = l2 != null ? l2.val : 0;

int add = s1 + s2 + pp;

pp = add >= 10 ? 1 : 0;

add = add >= 10 ? add - 10 : add;

cur.next = new ListNode(add);

cur = cur.next;

if (l1 != null) {

l1 = l1.next;

}

if (l2 != null) {

l2 = l2.next;

}

}

return p.next;

}

}