-6

How can we get the digits of num := 658943 in Golang? I need to print each digit value from the given number (num) as integer instead of string.

package main

import "fmt"

func main() {
    var (
        num    = 68932
        digits []int
    )

    // do something with num, insert the result to digits

    for _, val := range digits {
        fmt.Println(val)
    }
}

// expected output
// 6
// 8
// 9
// 3
// 2
anantadwi13
  • 75
  • 1
  • 6
vinodh kumar
  • 137
  • 2
  • 10

1 Answers1

0

You can use strconv

package main

import (
    "fmt"
    "strconv"
)

func main() {

    var (
        num    = 68932
        digits []int
    )

    s := strconv.Itoa(num)

    for _, n := range s {
        digits = append(digits, int(n-'0'))
    }

    for _, val := range digits {
        fmt.Println(val)
    }
}

https://go.dev/play/p/AHzwHPd7GJC

Ahmed Ali
  • 41
  • 1
  • 5