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:
- Skip leading spaces.
- An optional single
+or-sign. - Read digits until a non-digit; no digits at all means
0. - Clamp the value to
[-2147483648, 2147483647]on overflow.
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
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.
What it practices
- String processing
- Parse, scan and match text character by character with correct edge cases.
Related katas
- Decode String Medium Free Expand k[encoded] patterns, nesting included.
- Count Substring Occurrences Medium Free Count overlapping occurrences by comparing characters, not slicing strings.
- Hex Checksum Medium Free Sum the bytes of a hex string with nibble arithmetic, not substrings.
- Integer to Roman Medium Free Write Roman numerals the way Romans did - greedily.