LeetCode 2 - Add Two Numbers
原题如下:
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
题目比较简单,需要注意边界情况的处理和链表指针的使用,代码如下:
1 class ListNode { 2 int val; 3 ListNode next; 4 5 ListNode(int x) { 6 val = x; 7 next = null; 8 } 9 } 10 11 public class AddTwoNumbers2 { 12 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 13 ListNode head = null; 14 ListNode ll1 = l1; 15 ListNode ll2 = l2; 16 int res = 0; 17 ListNode cur = null; 18 while (true) { 19 int curval = 0; 20 curval += res; 21 if (ll1 == null && ll2 == null) { 22 if (curval != 0) { 23 cur.next = new ListNode(curval); 24 } 25 break; 26 } 27 if (ll1 != null) { 28 curval += ll1.val; 29 ll1 = ll1.next; 30 } 31 if (ll2 != null) { 32 curval += ll2.val; 33 ll2 = ll2.next; 34 } 35 if (curval >= 10) { 36 res = 1; 37 curval -= 10; 38 } else { 39 res = 0; 40 } 41 if (cur == null) { 42 head = cur = new ListNode(curval); 43 } else { 44 cur.next = new ListNode(curval); 45 cur = cur.next; 46 } 47 } 48 return head; 49 } 50 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· AI Agent爆火后,MCP协议为什么如此重要!
· dotnet 源代码生成器分析器入门
· Draw.io:你可能不知道的「白嫖级」图表绘制神器
· ASP.NET Core 模型验证消息的本地化新姿势
· 从零开始:基于 PyTorch 的图像分类模型