Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang: int to slice conversion

Tags:

slice

indexing

go

Total golang (and programming) noob!

Given any six digit number, how could one output a slice where each character of that number is assigned an individual location within the slice?

For instance, a slice (let's call it s) containing all of these characters, would have s[0]=first digit, s[1]=second digit, s[2]=third digit and so on.

Any help would be greatly appreciated!

like image 601
DoctorJoy Avatar asked Oct 25 '25 11:10

DoctorJoy


2 Answers

func IntToSlice(n int64, sequence []int64) []int64 {
    if n != 0 {
        i := n % 10
        // sequence = append(sequence, i) // reverse order output
        sequence = append([]int64{i}, sequence...)
        return IntToSlice(n/10, sequence)
    }
    return sequence
}
like image 73
MBB Avatar answered Oct 28 '25 04:10

MBB


The above answers are correct. Here comes another version of MBB's answer. Avoiding recursion and efficient reverting may increase performance and reduce RAM consumption.

package main

import (
    "fmt"
)

func reverseInt(s []int) {
    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
            s[i], s[j] = s[j], s[i]
    }
}

func splitToDigits(n int) []int{
    var ret []int
    
    for n !=0 {
        ret = append(ret, n % 10)
        n /= 10
    }
    
    reverseInt(ret)
    
    return ret
}

func main() {
    for _, n := range splitToDigits(12345) {
        fmt.Println(n)
    }
}

https://play.golang.org/p/M3aOUnNIbdv

like image 42
Michał B. Avatar answered Oct 28 '25 04:10

Michał B.