Bird
Raised Fist0
DSA Rustprogramming~10 mins

String to Integer atoi in DSA Rust - Execution Trace

Choose your learning style10 modes available
Concept Flow - String to Integer atoi
Start
↓
Skip leading spaces
↓
Check sign: '+' or '-'
↓
Read digits one by one
↓
Convert char to digit and build number
↓
Check overflow
↓
Apply sign
↓
Return integer
The process reads the string from left to right, skipping spaces, detecting sign, converting digits to number, checking overflow, and returning the final integer.
Execution Sample
DSA Rust
fn my_atoi(s: &str) -> i32 {
    let s = s.trim_start();
    let mut chars = s.chars().peekable();
    let mut sign = 1;
    let mut result: i32 = 0;
    if let Some(&c) = chars.peek() {
        if c == '-' { sign = -1; chars.next(); } else if c == '+' { chars.next(); }
    }
    while let Some(c) = chars.next() {
        if !c.is_digit(10) { break; }
        let digit = c.to_digit(10).unwrap() as i32;
        if result > (i32::MAX - digit) / 10 { return if sign == 1 { i32::MAX } else { i32::MIN }; }
        result = result * 10 + digit;
    }
    result * sign
}
This Rust function converts a string to a 32-bit signed integer following atoi rules.
Execution Table
StepOperationCurrent CharSignResult BeforeDigitResult AfterOverflow CheckVisual State
1Skip spaces' ' (space)10-0NoResult=0, sign=1
2Check sign'-'-10-0NoResult=0, sign=-1
3Read digit'4'-1044NoResult=4, sign=-1
4Read digit'2'-14242NoResult=42, sign=-1
5Read digit'8'-1428428NoResult=428, sign=-1
6Read digit'3'-142834283NoResult=4283, sign=-1
7Read digit'a' (non-digit)-14283-4283NoStop reading digits
8Apply sign--14283--4283NoFinal result = -4283
9Return--1-4283--4283NoReturn -4283
💡 Stopped reading digits at non-digit character 'a', then applied sign and returned result.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5After Step 6After Step 7Final
sign11-1-1-1-1-1-1-1
result00044242842834283-4283
current_char --4283a-
Key Moments - 3 Insights
Why do we stop reading digits when we encounter a non-digit character?
As shown in execution_table step 7, when the current character is 'a' (non-digit), the loop breaks to avoid invalid number formation.
How is overflow detected and handled?
Before adding a new digit, the code checks if result > (i32::MAX - digit) / 10 to prevent overflow, returning i32::MAX or i32::MIN accordingly (not shown in this example as no overflow occurs).
Why do we apply the sign after reading all digits?
The sign is stored separately (see variable_tracker 'sign'), and applied at the end (execution_table step 8) to keep digit processing simple and consistent.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4, what is the value of 'result' after processing character '2'?
A4
B42
C2
D0
💡 Hint
Check the 'Result After' column at step 4 in execution_table.
At which step does the function stop reading digits?
AStep 5
BStep 6
CStep 7
DStep 8
💡 Hint
Look for the first non-digit character in the 'Current Char' column in execution_table.
If the input string started with '+', how would the 'sign' variable change after step 2?
Asign would be 1
Bsign would be -1
Csign would be 0
Dsign would be unchanged from start
💡 Hint
Refer to the 'sign' variable in variable_tracker after step 2.
Concept Snapshot
String to Integer (atoi) conversion:
- Skip leading spaces
- Detect optional '+' or '-' sign
- Convert digits to number until non-digit
- Check for overflow before adding digit
- Apply sign and return integer
Full Transcript
This visual trace shows how a string is converted to an integer using the atoi method. The process starts by skipping spaces, then checking for a sign character. It reads digits one by one, converting each to a number and building the result. If a non-digit is found, reading stops. Overflow is checked before adding each digit. Finally, the sign is applied and the integer is returned. The example input had a leading space, a negative sign, digits '4', '2', '8', '3', and then a non-digit 'a' which stopped the reading. The final result was -4283.

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