989. Add to Array-Form of Integer
/** * 989. Add to Array-Form of Integer * https://leetcode.com/problems/add-to-array-form-of-integer/description/ * For a non-negative integer X, the array-form of X is an array of its digits in left to right order. * For example, if X = 1231, then the array form is [1,2,3,1]. Given the array-form A of a non-negative integer X, return the array-form of the integer X+K. Example 1: Input: A = [1,2,0,0], K = 34 Output: [1,2,3,4] Explanation: 1200 + 34 = 1234 Example 2: Input: A = [2,7,4], K = 181 Output: [4,5,5] Explanation: 274 + 181 = 455 Example 3: Input: A = [2,1,5], K = 806 Output: [1,0,2,1] Explanation: 215 + 806 = 1021 * */ class Solution { fun addToArrayForm(A: IntArray, K: Int): List<Int> { val result = ArrayList<Int>() val kStr = K.toString() var i = A.size - 1 var j = kStr.length - 1 var carry = 0 while (i >= 0 || j >= 0) { var temp = 0 if (i >= 0) { temp += A[i] } if (j >= 0) { temp += (kStr[j].toInt() - '0'.toInt()) } temp += carry if (temp >= 10) { /* 也学习下英文: * 个位 ones place * 个位数 ones digit * 十位 tens place * 十位数 tens digit * 百位 hundreds place * 百位数 hundreds digit * 千位 thousands place * 千位数 thousands digit * */ carry = temp / 10//get carry, if temp is 15 then carry is 1 temp = temp % 10//get ones digit, if temp is 15 then ones digit is 5 } else { carry = 0 } result.add(0, temp) i-- j-- } if (carry != 0){ result.add(0, carry) } return result } }
【推荐】国内首个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-03-06 ubuntu18下使用Shadowsocks-Qt5