[Golang] Atoi for Decimal Integer
Introduction
I read the post of Write your own atoi() in GeeksforGeeks [1], and feel it is a good exercise to implement my own atoi in Go, that takes a string (which represents an decimal integer) as an argument and returns its value in int type.
Go standard library already provides this function, see strconv.Atoi for more information.
atoi Implementation
import (
"errors"
)
var m = map[rune]int{
'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
}
// input: string of decimal integer number
func Atoi(ds string) (di int, err error) {
if len(ds) == 0 {
err = errors.New("input length is zero")
return
}
sign := 1
if ds[0] == '-' {
sign = -1
ds = ds[1:]
if len(ds) == 0 {
err = errors.New("invalid input: -")
return
}
}
for _, digit := range ds {
if d, ok := m[digit]; ok {
di = di*10 + d
} else {
err = errors.New("invalid digit: " + string(digit))
return
}
}
di = di * sign
return
}
Tested on: Go Playground
References
[1] | Write your own atoi() - GeeksforGeeks |