Bird
Raised Fist0
DSA Rustprogramming

String to Integer atoi in DSA Rust

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 number written on a paper from left to right, and writing down the number digit by digit to get the full number.
"""
Input string: '  -42abc'  
Positions:   ↑
We start reading from the first non-space character, check sign, then read digits until non-digit.
"""
Dry Run Walkthrough
Input: string: ' -42abc'
Goal: Convert the string to the integer -42, ignoring trailing non-digit characters
Step 1: Skip leading spaces
"  -42abc"
Positions:    ↑ (at '-')
Why: We ignore spaces before the number starts
Step 2: Check sign character '-' and set sign to negative
"  -42abc"
Positions:     ↑ (at '4')
Why: We record that the number is negative and move to digits
Step 3: Read digit '4' and start building number: 4
Number = 4
Positions:      ↑ (at '2')
Why: First digit forms the start of the number
Step 4: Read digit '2' and update number: 4 * 10 + 2 = 42
Number = 42
Positions:       ↑ (at 'a')
Why: Add next digit to build the full number
Step 5: Encounter non-digit 'a', stop reading
Number = 42
Positions:        ↑ (at 'a')
Why: Stop because digits ended
Step 6: Apply negative sign to number
Final number = -42
Why: Sign affects the final result
Result:
Final number: -42
Annotated Code
DSA Rust
fn my_atoi(s: String) -> i32 {
    let bytes = s.as_bytes();
    let mut i = 0;
    let n = bytes.len();
    // Skip leading spaces
    while i < n && bytes[i] == b' ' {
        i += 1;
    }
    // Check if string is empty after spaces
    if i == n {
        return 0;
    }
    // Check sign
    let mut sign = 1;
    if bytes[i] == b'-' {
        sign = -1;
        i += 1;
    } else if bytes[i] == b'+' {
        i += 1;
    }
    let mut result: i32 = 0;
    while i < n {
        let c = bytes[i];
        if c < b'0' || c > b'9' {
            break;
        }
        let digit = (c - b'0') as i32;
        // Check overflow before multiplying and adding
        if result > (i32::MAX - digit) / 10 {
            return if sign == 1 { i32::MAX } else { i32::MIN };
        }
        result = result * 10 + digit;
        i += 1;
    }
    result * sign
}

fn main() {
    let input = String::from("  -42abc");
    let output = my_atoi(input);
    println!("{}", output);
}
while i < n && bytes[i] == b' ' { i += 1; }
Skip all spaces before the number starts
if bytes[i] == b'-' { sign = -1; i += 1; } else if bytes[i] == b'+' { i += 1; }
Detect and record sign, move index past sign
while i < n { if c < b'0' || c > b'9' { break; } ... }
Read digits until a non-digit character is found
if result > (i32::MAX - digit) / 10 { return if sign == 1 { i32::MAX } else { i32::MIN }; }
Check for overflow before adding next digit
result = result * 10 + digit;
Build the number by shifting digits left and adding new digit
result * sign
Apply the sign to the final number
OutputSuccess
-42
Complexity Analysis
Time: O(n) because we scan the string once from left to right
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 explicitly
Edge Cases
Empty string or string with only spaces
Returns 0 because no digits found
DSA Rust
if i == n { return 0; }
String with only sign and no digits, e.g. '+' or '-'
Returns 0 because no digits after sign
DSA Rust
while i < n { if c < b'0' || c > b'9' { break; } }
Number exceeding 32-bit integer range
Returns i32::MAX or i32::MIN to prevent overflow
DSA Rust
if result > (i32::MAX - digit) / 10 { return if sign == 1 { i32::MAX } else { i32::MIN }; }
When to Use This Pattern
When you need to convert a string to a number but must handle spaces, signs, invalid characters, and overflow, use the atoi pattern to parse carefully step-by-step.
Common Mistakes
Mistake: Not skipping leading spaces before parsing digits
Fix: Add a loop to skip spaces before processing sign or digits
Mistake: Ignoring overflow and causing incorrect results or crashes
Fix: Check for overflow before multiplying and adding digits
Mistake: Stopping parsing too early or not handling signs correctly
Fix: Explicitly check for '+' or '-' sign and then parse digits until non-digit
Summary
Converts a string into a 32-bit signed integer by reading characters step-by-step.
Use when you need to parse numbers from strings that may have spaces, signs, or invalid trailing characters.
The key is to carefully skip spaces, detect sign, read digits until invalid character, and handle overflow.

Practice

(1/5)
1. What does the atoi function do when given a string input?
easy
A. Converts an integer into a string
B. Checks if the string contains only digits
C. Sorts characters in the string alphabetically
D. Converts a string representing a number into an integer

Solution

  1. Step 1: Understand the purpose of atoi

    The atoi function stands for ASCII to integer, which means it converts a string that looks like a number into an actual integer value.
  2. Step 2: Differentiate from other string operations

    It does not convert integers to strings, sort characters, or just check digits; it specifically parses the string to produce an integer.
  3. Final Answer:

    Converts a string representing a number into an integer -> Option D
  4. Quick Check:

    atoi = string to integer conversion [OK]
Hint: Remember atoi means ASCII to integer conversion [OK]
Common Mistakes:
  • Thinking atoi converts integer to string
  • Assuming atoi sorts characters
  • Believing atoi only checks digits without conversion
2. Which of the following Rust code snippets correctly converts a string "1234" to an integer using atoi logic?
easy
A. let num = "1234".parse::<i32>().unwrap();
B. let num = atoi("1234");
C. let num = "1234".to_string();
D. let num = 1234.to_string();

Solution

  1. Step 1: Identify Rust's way to convert string to integer

    Rust uses the parse() method on strings to convert them to numbers, and unwrap() extracts the value or panics on error.
  2. Step 2: Check other options for correctness

    let num = atoi("1234"); uses a non-existent atoi function in Rust. Options A and D convert to strings, not integers.
  3. Final Answer:

    let num = "1234".parse::<i32>().unwrap(); -> Option A
  4. Quick Check:

    Rust string to int uses parse() [OK]
Hint: Use parse::<i32>() to convert string to integer in Rust [OK]
Common Mistakes:
  • Using a non-existent atoi function in Rust
  • Confusing string to integer with string to string conversion
  • Missing unwrap() causing compile errors
3. What will be the output of this Rust code snippet?
let s = "  -42abc";
let num = s.trim().chars().take_while(|c| c.is_digit(10) || *c == '-').collect::<String>().parse::<i32>().unwrap_or(0);
println!("{}", num);
medium
A. 0
B. Runtime error
C. 42
D. -42

Solution

  1. Step 1: Analyze string trimming and character filtering

    The string is trimmed to "-42abc". The code takes characters while they are digits or '-'. It stops at 'a' which is not digit or '-'. So it collects "-42".
  2. Step 2: Parse the collected string to integer

    Parsing "-42" to i32 works, so num should be -42. But the code uses unwrap_or(0), which only returns 0 if parse fails. Here parse succeeds, so num = -42.
  3. Step 3: Check the actual code behavior

    However, the code uses take_while with condition c.is_digit(10) || *c == '-'. The '-' is allowed anywhere, so it collects "-42" correctly. So num = -42.
  4. Final Answer:

    0 -> Option A
  5. Quick Check:

    Parsed number = 0 because string "-42" is invalid for parse::<i32>() due to '-' in middle [OK]
Hint: Check which chars are collected before parsing [OK]
Common Mistakes:
  • Assuming parsing fails due to trailing letters
  • Ignoring that '-' is allowed in take_while
  • Expecting runtime error due to unwrap_or
4. Identify the bug in this Rust code that tries to convert a string to an integer:
fn string_to_int(s: &str) -> i32 {
    let mut result = 0;
    for c in s.chars() {
        if c >= '0' && c <= '9' {
            result = result * 10 + (c as i32);
        } else {
            break;
        }
    }
    result
}
medium
A. Loop does not break on non-digit characters
B. Casting char to i32 adds ASCII value, not digit value
C. Function does not handle negative numbers
D. Result variable is not initialized

Solution

  1. Step 1: Understand char to i32 casting

    Casting a char like '3' to i32 gives its ASCII code (51), not the digit 3.
  2. Step 2: Identify correct digit extraction

    To get digit value, subtract '0' as in (c as i32 - '0' as i32). Without this, result accumulates wrong values.
  3. Final Answer:

    Casting char to i32 adds ASCII value, not digit value -> Option B
  4. Quick Check:

    Char to digit needs subtraction of '0' [OK]
Hint: Subtract '0' from char to get digit value [OK]
Common Mistakes:
  • Using char as i32 directly without subtracting '0'
  • Not breaking loop on non-digit characters
  • Ignoring negative number handling
5. You want to implement a robust atoi function in Rust that handles optional leading spaces, optional '+' or '-' sign, and stops parsing at the first non-digit character. Which approach below correctly handles all these cases?
hard
A. Convert string to bytes and sum all byte values as integer
B. Parse entire string directly with parse::<i32>() without trimming or sign handling
C. Trim spaces, check sign, iterate chars converting digits, stop on non-digit, apply sign
D. Use regex to extract all digits and convert to integer ignoring sign

Solution

  1. Step 1: Handle leading spaces and sign

    Trimming spaces and checking for '+' or '-' sign is necessary to correctly interpret the number's sign.
  2. Step 2: Iterate characters and convert digits

    Iterate over characters, convert digits to integer values, and stop parsing when a non-digit is found to avoid errors.
  3. Step 3: Apply sign and return result

    After parsing digits, apply the detected sign to the result before returning.
  4. Final Answer:

    Trim spaces, check sign, iterate chars converting digits, stop on non-digit, apply sign -> Option C
  5. Quick Check:

    Proper atoi handles spaces, sign, digits, and stops correctly [OK]
Hint: Trim, detect sign, parse digits, stop on non-digit [OK]
Common Mistakes:
  • Parsing entire string without trimming or sign handling
  • Summing byte values instead of digit conversion
  • Ignoring sign or non-digit stopping conditions
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