Count golang number size

Asked

Viewed 362 times

3

I have a variable int, I need to know how many houses she has and capture the number for each house, for example my number is 57890, I need you to return the house quantity of that number, 57890 = 5. I also need the number that is present in each position 3 = 8.

  • 1

    You took an ambiguous example. Could you say who would be index number 0? And index 1?

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site

2 answers

6

The easiest way is to convert with Itoa() for text and pick up the characters with len(). But you can do it mathematically too (module math).

package main
import ("fmt"
        "strconv"
        "math")

func main() {
    t := strconv.Itoa(57890)
    fmt.Println("Tamanho matematicamente calculado:", math.Floor(math.Log10(math.Abs((57890)))) + 1)
    for i := 0; i < len(t); i++ {
        fmt.Printf("%c\n", t[i])
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I took element 2 because the index starts at 0, so the third is number 2.

Note that conversions are not necessary as there will only be ASCII characters.

  • Missing answer on number in index 3

  • 1

    @Jeffersonquesado truth, I was in a hurry, I did now. I took and did mathematically too, now it’s as he asked in the question.

1

For the first case use the method strconv.Itoa() to convert the numeric value to string and the method len() to check the size of it. For the second situation, use rune(str)[position] in which, position represents the position of string passed as parameter. Remembering you said position 3, however as the vector starts with 0, the return on position 3 would be 9. Behold:

package main
import ("fmt"
        "strconv")

func main() {
    str := strconv.Itoa(57890)
    fmt.Println(len(str))

    // index inicia com 0. então 2 representa a posição 3
    fmt.Println(string([]rune(str)[0])) // saida 5
    fmt.Println(string([]rune(str)[1])) // saida 7
    fmt.Println(string([]rune(str)[2])) // saida 8
}

Behold funfando no play golang.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.