2. 两数相加 Add Two Numbers
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
方法一:
由于链表是逆向存储,所以可以从第一位开始对应相加,carry是进位,sum = (n1+n2+carry)%10, carry = n1+n2+carry/10. 相加到两个链表都结束.最后看carry是否大于0.
为方便,可以new 一个head节点。
static class ListNode{ int val; ListNode next; ListNode(int x) { val = x; } } public ListNode addTwoNumbers(ListNode l1, ListNode l2){ ListNode dumpy = new ListNode(-1); ListNode cur = dumpy; int carry = 0; while(l1 != null || l2!= null){ int d1 = l1 == null ? 0 : l1.val; int d2 = l2 == null ? 0 : l2.val; int sum = d1 + d2 + carry; carry = sum >= 10 ? 1: 0; cur.next = new ListNode(sum % 10); cur = cur.next; if(l1 != null) l1 = l1.next; if(l2 != null ) l2 = l2.next; } if(carry == 1) cur.next = new ListNode(1); return dumpy.next; }
时间复杂度O(max(m,n))
方法二:
可以用递归
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { return addTwoNumbers(l1, l2, 0); } ListNode addTwoNumbers(ListNode l, ListNode r, int i) { if (l == null && r == null && i == 0) return null; int sum = (l != null ? l.val : 0) + (r != null ? r.val : 0) + i; var node = new ListNode(sum % 10); node.next = addTwoNumbers(l != null ? l.next : null, r != null ? r.next : null, sum / 10); return node; }
参考链接:
https://leetcode.com/problems/add-two-numbers/
https://leetcode-cn.com/problems/add-two-numbers/
分类:
leetcode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具