How to convert a list of digits to an integer add 1 and convert it back to a list of digits in Kotlin

1 Answer

0 votes
fun convertListOfDigitsToInt(digits: List<Int>): Int {
    var n = 0
    for (digit in digits) {
        n = n * 10 + digit
    }
    return n
}

fun convertIntToListOfDigits(digits: MutableList<Int>, n: Int) {
    var number = n
    var i = digits.size - 1
    while (number > 0 && i >= 0) {
        digits[i] = number % 10 // Extract the last digit
        number /= 10           // Remove the last digit
        i--
    }
}

fun main() {
    val list = mutableListOf(9, 4, 6, 9) // Initial list of digits

    // Convert the list of digits to an integer
    var n = convertListOfDigitsToInt(list)

    // Increment the integer
    n += 1

    // Convert the incremented integer back to a list of digits
    convertIntToListOfDigits(list, n)

    // Print the results
    println("n = $n")
    println(list.joinToString(", ", "[", "]"))
}

   
      
/*
run:

n = 9470
[9, 4, 7, 0]
  
*/

 



answered Apr 12, 2025 by avibootz
edited Apr 12, 2025 by avibootz
...