How to convert an array of digits to a number in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "strconv"
)

// ------------------------------------------------------------
// digitsToNumberMath
// Pure mathematical folding (no string operations).
// Example: [1,2,3,4] → 1234
// ------------------------------------------------------------
func digitsToNumberMath(digits []int) int {
    n := 0
    for _, d := range digits {
        n = n*10 + d
    }
    return n
}

// ------------------------------------------------------------
// digitsToNumberString
// Converts digits to strings, concatenates, then parses.
// Example: [1,2,3,4] → "1234" → 1234
// ------------------------------------------------------------
func digitsToNumberString(digits []int) int {
    s := ""
    for _, d := range digits {
        s += fmt.Sprint(d)
    }
    n, _ := strconv.Atoi(s)
    return n
}

func main() {
    digits := []int{4, 6, 3, 9, 1, 2}

    fmt.Println("Using math:   ", digitsToNumberMath(digits))
    fmt.Println("Using string: ", digitsToNumberString(digits))
}


/*
run:

Using math:    463912
Using string:  463912

*/

 



answered Jan 6, 2025 by avibootz
edited 2 days ago by avibootz
...