LeetCode 2. Add Two Numbers (两数相加)
题目标签:Linked List, Math
题目给了我们两个 Linked List, 各代表一个数字,不过顺序的反的。让我们把两个数字相加。
和普通的相加其实差不多,只不过变成了 Linked List, 还是要用到 / 和 %,具体看code。
Java Solution:
Runtime: 2ms, faster than 87%
Memory Usage: 44MB, less than 85%
完成日期:07/05/2019
关键点:利用 / 取得 carry;利用 % 取得 余数
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode dummyHead = new ListNode(0); ListNode cursor1 = l1; ListNode cursor2 = l2; ListNode cursor3 = dummyHead; int carry = 0; while(cursor1 != null || cursor2 != null) // go through both list { // if node exists, get the value, elsewise, default 0 int num1 = 0; int num2 = 0; if(cursor1 != null) num1 = cursor1.val; if(cursor2 != null) num2 = cursor2.val; int sum = num1 + num2 + carry; // update carry and sum carry = sum / 10; cursor3.next = new ListNode(sum % 10); cursor3 = cursor3.next; // move both list to next node if(cursor1 != null) cursor1 = cursor1.next; if(cursor2 != null) cursor2 = cursor2.next; } // at last, still need to check carry for last digit if(carry == 1) cursor3.next = new ListNode(1); return dummyHead.next; } }
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· 软件产品开发中常见的10个问题及处理方法
· Vite CVE-2025-30208 安全漏洞
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· MQ 如何保证数据一致性?
2017-07-07 LeetCode 437. Path Sum III (路径之和之三)