fundfs(num: String, preSum: String, preNum: String, start: Int, k: Int): Boolean { if (k > 2 && start >= num.length) { returntrue } var len = 1 while (len + start <= num.length) { val sum = isSum(num, start, start + len, preSum, k) if (sum != "-1") { if (dfs(num, add(sum, preNum), sum, start + len, k + 1)) returntrue } len++ } returnfalse }
privatefunisSum(num: String, start: Int, end: Int, preSum: String, k: Int): String { if (num[start] == '0' && start < end - 1) return"-1" val sum = num.substring(start, end) if (k < 2) return sum returnif (preSum == sum) sum else "-1" }
//两个字符串相加 funadd(str1: String, str2: String): String { var str2 = str2 if (str1.length < str2.length) return add(str2, str1)
val size1 = str1.length val size2 = str2.length val sb = StringBuilder() for (i in0 until size1 - size2) { sb.append('0') } str2 = sb.toString() + str2
val result = StringBuilder(str1) var sgn = 0 for (i in size1 - 1 downTo 0) { val num = str1[i] - '0' + str2[i].toInt() - '0'.toInt() + sgn result.setCharAt(i, (num % 10 + '0'.toInt()).toChar()) sgn = num / 10 } returnif (sgn == 1) "1$result"else String(result) }