445. Add Two Numbers II
package LeetCode_445 import LeetCode_2.ListNode /** * 445. Add Two Numbers II * https://leetcode.com/problems/add-two-numbers-ii/description/ * * You are given two non-empty linked lists representing two non-negative integers. * The most significant digit comes first and each of their nodes contain a single digit. * Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Follow up: What if you cannot modify the input lists? In other words, reversing the lists is not allowed. Example: Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 8 -> 0 -> 7 * */ class Solution { /* * Time complexity:O(max(m,n)), Space complexity:O(max(m,n)) * */ fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? { val str1 = ListNodeToString(l1) val str2 = ListNodeToString(l2) val array1 = str1.toCharArray() val array2 = str2.toCharArray() var i = array1.size - 1 var j = array2.size - 1 var carry = 0 val sb = StringBuilder() while (i >= 0 || j >= 0) { val value1 = if (i >= 0) array1[i--] - '0' else 0 val value2 = if (j >= 0) array2[j--] - '0' else 0 var temp = value1 + value2 + carry if (temp >= 10) { carry = temp / 10 temp %= 10 } else { carry = 0 } sb.insert(0, temp) } if (carry != 0) { sb.insert(0, 1) } val dummy = ListNode(0) var tail = dummy for (item in sb) { tail.next = ListNode(item - '0') tail = tail.next!! } return dummy.next } private fun ListNodeToString(l1_: ListNode?): String { var l1 = l1_ val sb = StringBuilder() while (l1 != null) { sb.append(l1.`val`) l1 = l1.next } return sb.toString() } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
2019-06-26 android studio 安装APP时出现错误:xxx/build/intermediates/split-apk/armv7/debug/slices/slice_x.apk 的解决方式