Programming & Development / April 8, 2025

LeetCode 8: String to Integer (atoi) in Go - Robust Parsing from Scratch

Go Golang LeetCode String to Integer Atoi Parsing Edge Cases Overflow Handling Go tutorial Coding Interview String Manipulation

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:

  1. Ignore leading whitespace.
  2. Optional + or - sign.
  3. Read digits until a non-digit is found.
  4. 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:

  1. Trim whitespace at the beginning.
  2. Capture sign (+ or -).
  3. Read digits while valid.
  4. 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.

Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex