gpt4 book ai didi

kotlin - Kotlin-字 rune 字与预期的Int类型不一致

转载 作者:行者123 更新时间:2023-12-02 13:03:26 26 4
gpt4 key购买 nike

我正在为程序的类型而苦苦挣扎,我被要求首先在JS中进行操作,并且效果很好,但现在我无法实现结果。
您认为我应该提出另一个“算法”吗?在此先感谢您的宝贵时间。

fun main(){
// the idea is to put numbers in a box
// that cant be larger than 10
val data = "12493419133"
var result = data[0]
var currentBox = Character.getNumericValue(data[0])
var i = 1

while(i < data.length){

val currentArticle = Character.getNumericValue(data[i])
currentBox += currentArticle

println(currentBox)

if(currentBox <= 10){
result += Character.getNumericValue(currentArticle)
}else{
result += '/'
//var resultChar = result.toChar()
// result += '/'
currentBox = Character.getNumericValue(currentArticle)
result += currentArticle
}
i++
}
print(result) //should print 124/9/341/91/33
}

最佳答案

结果实际上是Char类型,并且重载运算符函数+仅接受Int以增加ASCII值以获得新的Char。

public operator fun plus(other: Int): Char

以idomatic Kotlin方式,您可以解决您的问题:

fun main() {
val data = "12493419133"

var counter = 0
val result = data.asSequence()
.map(Character::getNumericValue)
.map { c ->
counter += c
if (counter <= 10) c.toString() else "/$c".also{ counter = c }
}
.joinToString("") // terminal operation, will trigger the map functions

println(result)
}

编辑:如果 data太大,则可能要使用StringBuilder,因为它不会在每次迭代字符时都创建字符串,并且可以使用 list.fold()来代替自己的计数器

fun main() {
val data = "12493419133"

val sb = StringBuilder()
data.fold(0) { acc, c ->
val num = Character.getNumericValue(c)
val count = num + acc
val ret = if (count > 10) num.also { sb.append('/') } else count
ret.also { sb.append(c) } // `ret` returned to ^fold, next time will be passed as acc
}

println(sb.toString())
}

关于kotlin - Kotlin-字 rune 字与预期的Int类型不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62444911/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com