I am doing the atoi problem in leetcode and I submitted my code below which isn't too important. I am wondering if it is a valid failure leetcode gave me. It seems like my code is doing the right thing.
Here is the problem description:
const (
MaxInt32 = 1<<31 - 1
MinInt32 = -1 << 31
)
func myAtoi(str string) int {
if len(str) < 1 {
return 0
}
// count to keep track of the number of digits
count := 0
// container for digits
values := make([]rune, 0)
// constant we are going to need
minus := "-"
plus := "+"
lastWasPrefix := false
// is the number negative or lead with dash
negative := false
clean := strings.TrimSpace(str)
for _, char := range clean {
isNumber := unicode.IsNumber(char)
isMinus := string(char) == minus
isPlus := string(char) == plus
isPrefix := isMinus || isPlus
// checking for two prefixes following eachother
if isPrefix && lastWasPrefix {
return 0
}
if isPrefix {
lastWasPrefix = true
}
curLen := len(values)
if !isNumber && !isPrefix && curLen == 0 {
return 0
}
if !isNumber && !isPrefix && curLen != 0 {
break
}
if isMinus {
negative = true
continue
}
if isNumber {
// add value in order and inc. count
values = append(values, char)
count++
}
}
postLen := len(values)
if postLen == 0 {
return 0
}
multiplier := int32(1)
ten := int32(10)
total := int32(0)
for i := postLen - 1; i >= 0; i-- {
diff := MaxInt32 - total
added := CharToNum(values[i]) * multiplier
// added will be zero if we overflow the int
if added > diff || added < 0 {
return MinInt32
}
total += added
multiplier *= ten
}
if negative {
return int(total * int32(-1))
} else {
return int(total)
}
}
/**
a rune is a uni code char so we need to conver from unicode int to digit
*/
func CharToNum(r rune) (int32) {
for i := 48; i <= 57; i++ {
if int(r) == i {
return int32(r) - 48
}
}
return -1
}
Any help understanding this error would be much appreciated. I don't want any help with the algorithm. Is this a valid error or not?