C++面试题(54)------把字符串转换成整数

  • 操作系统:ubuntu22.04
  • IDE:Visual Studio Code
  • 编程语言:C++11

题目描述

请你写一个函数,将字符串转换为整数(int)。

函数应忽略前导空格,可接受一个可选的正负号,然后是数字字符。

遇到非数字字符或字符串结束时停止解析。

如果解析结果超过 int 的表示范围,则返回 int 的最大值或最小值:

超过 2^31 - 1(即 0x7FFFFFFF) → 返回 INT_MAX
小于 -2^31(即 -0x80000000) → 返回 INT_MIN

示例:

输入: "42"
输出: 42

输入: "   -42"
输出: -42

输入: "4193 with words"
输出: 4193

输入: "words and 987"
输出: 0

输入: "-91283472332"
输出: -2147483648 (INT_MIN)

解法思路:模拟 atoi 函数实现

这是一道经典的字符串处理 + 边界判断题,考察你对各种边界情况的处理能力。


#include 
#include 
#include 

using namespace std;

class Solution {
public:
    int strToInt( string str )
    {
        int n         = str.size();
        int i         = 0;
        int sign      = 1;
        long long res = 0;

        // 1. 跳过前导空格
        while ( i < n && isspace( str[ i ] ) )
            ++i;

        // 2. 处理符号
        if ( i < n && ( str[ i ] == '+' || str[ i ] == '-' ) )
        {
            sign = ( str[ i++ ] == '-' ) ? -1 : 1;
        }

        // 3. 处理数字部分
        while ( i < n && isdigit( str[ i ] ) )
        {
            int digit = str[ i++ ] - '0';

            // 判断是否溢出
            if ( res > INT_MAX / 10 || ( res == INT_MAX / 10 && digit > INT_MAX % 10 ) )
            {
                return ( sign == 1 ) ? INT_MAX : INT_MIN;
            }

            res = res * 10 + digit;
        }

        return sign * res;
    }
};

int main()
{
    Solution s;
    cout << s.strToInt( "42" ) << endl;
    cout << s.strToInt( "   -42" ) << endl;
    cout << s.strToInt( "4193 with words" ) << endl;
    cout << s.strToInt( "words and 987" ) << endl;
    cout << s.strToInt( "-91283472332" ) << endl;
}

运行结果

42
-42
4193
0
-2147483648

你可能感兴趣的:(c++,c++,算法,开发语言)