我正在为程序的类型而苦苦挣扎,我被要求首先在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())
}

07-24 09:49
查看更多