Created
February 21, 2019 19:56
-
-
Save BaReinhard/487ab564306eb2270738f68beec6f25f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// pseudo code | |
// strip string of white space | |
// check first character for sign | |
// loop through remaining string until the end or a non integer value | |
// check ascii value of each character and ensure it falls in proper range | |
// then offset the ascii value from the ascii of 0 | |
// return new integer with sign 1 or -1 | |
func myAtoi(str string) int { | |
finalString:= "" | |
sign:= 1 | |
// Trim whitespace from string | |
remainingString := strings.TrimSpace(str) | |
// Check if string is now empty | |
if remainingString == ""{ | |
return 0 | |
} | |
// check first digit to see if it is a sign or a number | |
switch(remainingString[0]){ | |
// if first rune is a positive digit copy string to finalString | |
case '0','1','2','3','4','5','6','7','8','9': | |
finalString= remainingString | |
// if first rune is a +, copy the string excluding the + | |
case '+': | |
finalString = remainingString[1:] | |
// if first rune is a -, copy the string excluding the - | |
case '-': | |
finalString= remainingString[1:] | |
sign = -1 | |
// if the first rune is anything else, this is a bad string | |
default: | |
fmt.Printf("Bad string") | |
return 0 | |
} | |
for idx, runeValue := range finalString{ | |
// loop until we find a non numeric rune or code point | |
// single digit int values range from '0'-'9' | |
if runeValue < '0' || runeValue > '9'{ | |
finalString = finalString[:idx] | |
break | |
} | |
} | |
returnVal := 0 | |
// loop through the remainging string and covert to an integer | |
for _,rVal := range finalString{ | |
// ensure to subtract the ascii val of '0' before converting to int | |
returnVal = returnVal*10 + int(rVal-'0') | |
// save some compute for long string values, check after each loop | |
if sign == 1 && returnVal > math.MaxInt32{ | |
return math.MaxInt32 | |
}else if sign == -1 && sign * returnVal < math.MinInt32{ | |
return math.MinInt32 | |
} | |
} | |
// finally return apply the sign | |
return returnVal * sign | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment