SoFunction
Updated on 2025-04-14

Detailed explanation of the code that implements string to integer (atoi) in C++

1. Problem description

In programming, you often encounter the need to convert strings into integers, just like the standard libraryatoiThe same function.

This question requires that one be realizedmyAtoiFunctions convert the input string into 32-bit signed integers. The specific rules are as follows:

  1. Read in the string and discard useless leading spaces.
  2. Check whether the next character (assuming that it has not yet reached the end of the character) is positive or negative, and read that character (if any). Determine whether the final result is a negative or positive number. If neither exists, the result is assumed to be positive.
  3. Read the next character until the next non-numeric character is reached or the end of the input is reached. The rest of the string will be ignored.
  4. Convert these numbers read in the previous step into integers (i.e., "123" -> 123, "0032" -> 32). If no number is read, the integer is 0 . Change the symbol if necessary (start from step 2).
  5. If the integer number exceeds the 32-bit signed integer range[−2^31, 2^31 − 1], this integer needs to be truncated to keep it within this range. Specifically, less than−2^31The integer should be fixed as−2^31, greater than2^31 − 1The integer should be fixed as2^31 − 1 。

2. Problem-solving ideas

To achievemyAtoiFunctions, we can follow the following steps:

  1. Ignore leading spaces: Starting from the beginning of the string, skip all space characters until the first non-space character is encountered.
  2. Processing symbols: Check whether the first non-space character is+or-,in the case of+, the result is a positive number; if so-, the result is a negative number; if there is no sign, the default result is a positive number.
  3. Convert numbers: Starting after the symbolic character, read the numeric characters in turn and convert them into integers. If non-numeric characters are encountered, the reading will stop.
  4. Overflow processing: During the conversion of numbers, it is necessary to check whether there will be overflow. If the result is beyond the range of 32-bit signed integers, the result needs to be truncated.

3. Code implementation

#include <iostream>
#include <string>
#include <climits>
 
class Solution {
public:
    int myAtoi(std::string str) 
    {
        int flag = 1;  // Positive and negative signs        int i = 0;     // Subscript        int ret = 0;   // result        int size = (); 
 
        // Ignore leading spaces        while (i < size && str[i] == ' ') {
            ++i;
        }
 
        // Process symbols        if (i < size && str[i] == '-') {
            flag = -1;
            ++i;
        } else if (i < size && str[i] == '+') {
            ++i;
        }
 
        // Convert numbers        while (i < size && str[i] >= '0' && str[i] <= '9') {
            int digit = str[i] - '0';
            // Check for overflow            if (ret > (INT_MAX - digit) / 10) {
                return flag == 1 ? INT_MAX : INT_MIN;
            }
            ret = ret * 10 + digit;
            ++i;
        }
 
        return flag * ret;
    }
};
 
int main() {
    Solution sol;
    std::string input = "   -42";
    std::cout << (input) << std::endl;
    return 0;
}

4. Detailed explanation of code logic

1. Variable Initialization

  • flag: The positive and negative sign used to record the result, the initial value is 1, indicating a positive number.
  • i: The subscript used to traverse the string, with an initial value of 0.
  • ret: Used to store the converted integer result, with an initial value of 0.
  • size: The length of the string.

2. Ignore leading spaces

while (i < size && str[i] == ' ') {
    ++i;
}

Use onewhileLoop, starting from the beginning of the string, skipping all space characters until the first non-space character is encountered.

3. Processing symbols

if (i < size && str[i] == '-') {
    flag = -1;
    ++i;
} else if (i < size && str[i] == '+') {
    ++i;
}

Check whether the first non-space character is+or-. in the case of-, thenflagSet to -1, indicating that the result is a negative number; if so+, the character is skipped directly; if there is no symbol, the default result is a positive number.

4. Convert numbers

while (i &lt; size &amp;&amp; str[i] &gt;= '0' &amp;&amp; str[i] &lt;= '9') {
    int digit = str[i] - '0';
    // Check for overflow    if (ret &gt; (INT_MAX - digit) / 10) {
        return flag == 1 ? INT_MAX : INT_MIN;
    }
    ret = ret * 10 + digit;
    ++i;
}

Use a while loop to read the numeric characters from after the symbolic characters. Converts the character to the corresponding number digit and adds it to the result ret. Before each update of ret, check if overflow occurs. If ret multiplying by 10 and adding digit will exceed INT_MAX, INT_MAX or INT_MIN will be returned based on the value of flag.

5. Return result

return flag * ret;

Finally, multiply the result byflag, get the final integer result and return.

This is the article about the detailed explanation of the code of C++ implementing string to integer (atoi). For more related C++ string to integer content, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!