Introduction
LeetCode 8: String to Integer (atoi) challenges you to convert a string to an integer, mimicking the behavior of the C/C++ atoi()
function. This involves meticulous handling of whitespace, signs, invalid characters, and overflow conditions.
In this article, we'll solve this problem in Go (Golang) with a clean and robust approach—perfect for interviews and real-world parsers.
Problem Statement
Implement the myAtoi(string s)
function, which converts a string to a 32-bit signed integer.
Rules:
- Ignore leading whitespace.
- Optional
+
or -
sign.
- Read digits until a non-digit is found.
- Clamp the number within [-2³¹, 2³¹ - 1].
Examples
go
Input: s = "42"
Output: 42
go
Input: s = " -42"
Output: -42
go
Input: s = "4193 with words"
Output: 4193
go
Input: s = "words and 987"
Output: 0
go
Input: s = "-91283472332"
Output: -2147483648 (clamped)
Approach: Manual Parsing
We’ll walk through the string and extract only valid characters that contribute to the number.
Steps:
- Trim whitespace at the beginning.
- Capture sign (
+
or -
).
- Read digits while valid.
- Check overflow and clamp if necessary.
Go Implementation
go
package main
import (
"fmt"
"math"
"unicode"
)
func myAtoi(s string) int {
i := 0
n := len(s)
result := 0
sign := 1
// Step 1: Skip leading whitespaces
for i < n && s[i] == ' ' {
i++
}
// Step 2: Check for optional sign
if i < n && (s[i] == '+' || s[i] == '-') {
if s[i] == '-' {
sign = -1
}
i++
}
// Step 3: Parse digits and build the number
for i < n && unicode.IsDigit(rune(s[i])) {
digit := int(s[i] - '0')
// Step 4: Handle overflow
if result > (math.MaxInt32-digit)/10 {
if sign == 1 {
return math.MaxInt32
} else {
return math.MinInt32
}
}
result = result*10 + digit
i++
}
return result * sign
}
func main() {
inputs := []string{"42", " -42", "4193 with words", "words and 987", "-91283472332"}
for _, input := range inputs {
fmt.Printf("Input: \"%s\" -> Output: %d\n", input, myAtoi(input))
}
}
Key Edge Cases Covered
- Empty or whitespace-only string → returns
0
- Leading/trailing spaces → trimmed
- Non-digit characters after digits → ignored
- Characters before digits → entire string ignored
- Integer overflow → clamped to
INT_MAX
/ INT_MIN
Time and Space Complexity
- Time Complexity: O(n) — one pass through the string
- Space Complexity: O(1) — constant memory usage
Key Takeaways
- This is a classic string parsing problem with lots of corner cases.
- Handle overflow before it happens by checking limits.
- Avoid using built-in parsing functions if you're asked to implement
atoi
logic manually.
- Writing your own parser helps understand how language internals work.