Bird
Raised Fist0
DSA C#programming

String to Integer atoi in DSA C#

Choose your learning style10 modes available
Mental Model
Convert a string of characters into a number by reading each digit one by one and building the number step by step.
Analogy: Like reading a price tag digit by digit and writing down the total price as a number in your notebook.
Input string: "  -42abc"
Positions:  [0] [1] [2] [3] [4] [5] [6]
Characters: ' '  '-'  '4'  '2'  'a'  'b'  'c'
Pointer:    ↑
Dry Run Walkthrough
Input: string: " -42abc"
Goal: Convert the initial part of the string to the integer -42, ignoring trailing letters.
Step 1: Skip leading spaces
Pointer moves to index 2: '-'  '4'  '2'  'a'  'b'  'c'
String: "  -42abc"
Pointer:       ↑
Why: Spaces do not affect the number, so we ignore them to find the sign or digits.
Step 2: Check for sign character '-'
Sign set to negative, pointer moves to index 3: '4'  '2'  'a'  'b'  'c'
String: "  -42abc"
Pointer:          ↑
Why: The '-' means the number is negative, so we remember this before reading digits.
Step 3: Read digit '4' and add to number
Number = 4
Pointer moves to index 4: '2'  'a'  'b'  'c'
String: "  -42abc"
Pointer:             ↑
Why: We start building the number by reading the first digit.
Step 4: Read digit '2' and update number to 42
Number = 4 * 10 + 2 = 42
Pointer moves to index 5: 'a'  'b'  'c'
String: "  -42abc"
Pointer:                ↑
Why: Each new digit shifts the number left by one decimal place and adds the digit.
Step 5: Encounter non-digit 'a', stop reading
Final number before sign: 42
Stop parsing
String: "  -42abc"
Why: Non-digit means the number part ended, so we stop.
Step 6: Apply sign to number
Number = -42
Why: We apply the negative sign found earlier to get the final result.
Result:
Final integer: -42
Annotated Code
DSA C#
using System;

public class Solution {
    public static int MyAtoi(string s) {
        int i = 0, n = s.Length, sign = 1, result = 0;
        // Skip leading spaces
        while (i < n && s[i] == ' ') i++;
        // Check for sign
        if (i < n && (s[i] == '+' || s[i] == '-')) {
            sign = s[i] == '-' ? -1 : 1;
            i++;
        }
        // Convert digits to number
        while (i < n && Char.IsDigit(s[i])) {
            int digit = s[i] - '0';
            // Check overflow
            if (result > (int.MaxValue - digit) / 10) {
                return sign == 1 ? int.MaxValue : int.MinValue;
            }
            result = result * 10 + digit;
            i++;
        }
        return sign * result;
    }

    public static void Main() {
        string input = "  -42abc";
        int output = MyAtoi(input);
        Console.WriteLine(output);
    }
}
while (i < n && s[i] == ' ') i++;
Skip all spaces at the start to find the first meaningful character.
if (i < n && (s[i] == '+' || s[i] == '-')) { sign = s[i] == '-' ? -1 : 1; i++; }
Detect if the number is negative or positive and move pointer forward.
while (i < n && Char.IsDigit(s[i])) {
Read each digit to build the number until a non-digit is found.
if (result > (int.MaxValue - digit) / 10) { return sign == 1 ? int.MaxValue : int.MinValue; }
Check if adding the next digit causes overflow and clamp the value.
result = result * 10 + digit; i++;
Add the digit to the number and move pointer forward.
return sign * result;
Apply the sign to the final number and return.
OutputSuccess
-42
Complexity Analysis
Time: O(n) because we scan the string once until digits end or string ends
Space: O(1) because we use only a few variables regardless of input size
vs Alternative: Compared to parsing with built-in functions, this manual method handles invalid input and overflow safely.
Edge Cases
Empty string ""
Returns 0 because no digits found
DSA C#
while (i < n && s[i] == ' ') i++;
String with only spaces " "
Returns 0 after skipping spaces and finding no digits
DSA C#
while (i < n && s[i] == ' ') i++;
String with number exceeding int max "9223372036854775808"
Returns int.MaxValue due to overflow check
DSA C#
if (result > (int.MaxValue - digit) / 10) { return sign == 1 ? int.MaxValue : int.MinValue; }
String with only sign and no digits "+"
Returns 0 because no digits follow the sign
DSA C#
while (i < n && Char.IsDigit(s[i])) {
When to Use This Pattern
When you see a problem asking to convert a string to a number with possible spaces and signs, use the atoi pattern to parse carefully digit by digit and handle invalid input.
Common Mistakes
Mistake: Not skipping leading spaces before parsing sign and digits
Fix: Add a loop to skip all spaces before checking sign or digits
Mistake: Not checking for overflow when building the number
Fix: Add a condition to detect overflow before multiplying and adding digits
Mistake: Stopping parsing only at string end, not at first non-digit
Fix: Stop parsing as soon as a non-digit character is found after optional sign
Summary
Converts a string into an integer by reading characters one by one, handling spaces, signs, digits, and overflow.
Use when you need to safely parse numbers from strings that may have extra characters or invalid input.
The key is to skip spaces, detect sign, read digits carefully, and stop at the first invalid character.

Practice

(1/5)
1. What does the atoi function do when given a string input?
easy
A. Reverses the string characters
B. Converts the string to a floating-point number
C. Converts the string to an integer number
D. Counts the number of characters in the string

Solution

  1. Step 1: Understand the purpose of atoi

    The atoi function is designed to convert a string that represents a number into an integer type.
  2. Step 2: Differentiate from other string operations

    It does not reverse or count characters, nor convert to floating-point; it specifically converts to integer.
  3. Final Answer:

    Converts the string to an integer number -> Option C
  4. Quick Check:

    atoi converts string to integer [OK]
Hint: atoi always converts string digits to integer number [OK]
Common Mistakes:
  • Thinking atoi converts to float
  • Confusing atoi with string reversal
  • Assuming atoi counts characters
2. Which of the following C# code snippets correctly converts a string "1234" to an integer using atoi logic?
easy
A. int num = Convert.ToString(1234);
B. int num = "1234".ToInt();
C. int num = int.ToString("1234");
D. int num = int.Parse("1234");

Solution

  1. Step 1: Identify correct C# method for string to int

    int.Parse(string) converts a numeric string to an integer correctly.
  2. Step 2: Check other options for syntax errors

    "1234".ToInt() and int.ToString("1234") are invalid methods; Convert.ToString(1234) converts int to string, not string to int.
  3. Final Answer:

    int num = int.Parse("1234"); -> Option D
  4. Quick Check:

    int.Parse converts string to int [OK]
Hint: Use int.Parse to convert string digits to int in C# [OK]
Common Mistakes:
  • Using invalid method names like ToInt()
  • Confusing Convert.ToString with conversion to int
  • Trying to call ToString on string input
3. What is the output of the following C# code?
string s = "  -42abc";
int result = MyAtoi(s);
Console.WriteLine(result);

int MyAtoi(string str) {
    int i = 0, sign = 1, num = 0;
    while (i < str.Length && str[i] == ' ') i++;
    if (i < str.Length && (str[i] == '+' || str[i] == '-')) {
        sign = (str[i] == '-') ? -1 : 1;
        i++;
    }
    while (i < str.Length && char.IsDigit(str[i])) {
        num = num * 10 + (str[i] - '0');
        i++;
    }
    return sign * num;
}
medium
A. Exception thrown
B. -42
C. 42
D. 0

Solution

  1. Step 1: Skip leading spaces and detect sign

    The code skips spaces, finds '-', sets sign to -1, then moves to digits.
  2. Step 2: Parse digits until non-digit

    It reads '4' and '2', stops at 'a', so number is 42, multiplied by sign -1 gives -42.
  3. Final Answer:

    -42 -> Option B
  4. Quick Check:

    Parsed number with sign = -42 [OK]
Hint: Skip spaces, check sign, parse digits until non-digit [OK]
Common Mistakes:
  • Not skipping spaces before sign
  • Parsing non-digit characters
  • Ignoring sign character
4. Identify the bug in this MyAtoi function and select the fix:
int MyAtoi(string str) {
    int i = 0, sign = 1, num = 0;
    while (str[i] == ' ') i++;
    if (str[i] == '+' || str[i] == '-') {
        sign = (str[i] == '-') ? -1 : 1;
        i++;
    }
    while (char.IsDigit(str[i])) {
        num = num * 10 + (str[i] - '0');
        i++;
    }
    return sign * num;
}
medium
A. Add boundary checks for index i before accessing str[i]
B. Remove the sign check to simplify code
C. Change char.IsDigit to char.IsLetter
D. Initialize num to -1 instead of 0

Solution

  1. Step 1: Check for index out of range errors

    The code accesses str[i] without checking if i < str.Length, risking runtime error.
  2. Step 2: Fix by adding boundary checks in all loops

    Adding conditions like i < str.Length in while loops prevents out-of-range exceptions.
  3. Final Answer:

    Add boundary checks for index i before accessing str[i] -> Option A
  4. Quick Check:

    Always check index bounds before accessing string [OK]
Hint: Always check string length before accessing characters [OK]
Common Mistakes:
  • Ignoring string length checks causing exceptions
  • Removing sign check breaks negative numbers
  • Using char.IsLetter instead of char.IsDigit
5. Given the input string "+-12", what should a robust atoi implementation return according to standard rules?
hard
A. 0
B. -12
C. 12
D. Exception thrown

Solution

  1. Step 1: Analyze sign characters in input

    The string starts with '+' followed immediately by '-', which is invalid for atoi parsing.
  2. Step 2: According to atoi rules, invalid sign sequence returns 0

    Parsing stops at invalid sequence, so result is 0.
  3. Final Answer:

    0 -> Option A
  4. Quick Check:

    Invalid sign sequence returns 0 [OK]
Hint: Invalid sign sequences return 0 in atoi [OK]
Common Mistakes:
  • Parsing multiple signs as valid
  • Returning partial number ignoring invalid signs
  • Throwing exceptions instead of returning 0
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard