How to convert an array of digits to an integer add 1 and convert it back to an array of digits in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

func convertArrayOfDigitsToIntNumber(arr []int) int {
    n := 0
    for _, digit := range arr {
        n = n*10 + digit
    }
    return n
}

func convertIntNumberToArrayOfDigits(digits []int, n int) {
    i := len(digits) - 1
    for n > 0 && i >= 0 {
        digits[i] = n % 10 // Extract last digit
        n = n / 10         // Remove the last digit
        i--
    }
}

func main() {
    // Initial array of digits
    arr := []int{9, 4, 6, 9}

    // Convert the array to an integer
    n := convertArrayOfDigitsToIntNumber(arr)

    // Increment the integer
    n++

    // Convert the integer back to an array of digits
    convertIntNumberToArrayOfDigits(arr, n)

    // Print the results
    fmt.Printf("n = %d\n", n)
    fmt.Println(arr)
}



/*
run:

n = 9470
[9 4 7 0]

*/

 



answered Apr 12, 2025 by avibootz
...