Skip to content
Katabench
Try free

String to Integer (atoi)

Medium About 20 min Free, no account needed

Parse a messy numeric prefix with correct clamping at the int limits.

The brief

Convert a string to a 32-bit signed integer with these exact rules:

  1. Skip leading spaces.
  2. An optional single + or - sign.
  3. Read digits until a non-digit; no digits at all means 0.
  4. Clamp the value to [-2147483648, 2147483647] on overflow.

The hidden trap

The visible tests fit comfortably in int. The hidden ones overflow it, an int (or even unchecked long) accumulator silently wraps where the spec says clamp. Accumulate in long and clamp as soon as the range is left.

Starter code

C#
using System;

public class Solution
{
    // TODO: return the numeric prefix parsed per the atoi rules.
    public int MyAtoi(string s)
    {
        throw new NotImplementedException();
    }
}

How it is graded

Visible examples help you iterate. Hidden tests then cover edge cases and larger inputs, and every test reports server-measured time and allocated bytes.

C# coding challenges →

What it practices

String processing
Parse, scan and match text character by character with correct edge cases.

Related katas