Sword refers to Offer67. Convert a string to an integer

  • Topic: Sword refers to Offer67. Convert a string to an integer to
    achieve stoi; if the
    conversion is not possible, return 0: ① str is empty ② only spaces ③ no numbers ④ The first valid character is not a sign or a number
    if the value exceeds int Range, return INT_MIN and INT_MAX, which are determined according to the first valid character bit'+' and'-'. If there is no sign, it will be counted as a positive number;

  • Ideas:
    1. Simulation traversal: time O(n): it needs to traverse at most once, if it cannot be converted, it will end in the middle, space O(1)

class Solution {
    
    
public:
    int strToInt(string str) {
    
    
        if (str.empty()) return 0;
        
        int n = str.size();
        int i = 0;
        while (i < n && str[i] == ' ') ++i;//跳过开头空格;
        if (str[i] == ' ') return 0;//str只有空格

        int symbol = 0;//标识正负号
        if (str[i] == '+') {
    
    
            symbol = 1;
            if (++i < n && !(str[i] >= '0' && str[i] <= '9')) return 0;//正负号后面没数字
        } 
        else if (str[i] == '-') {
    
    
            symbol = -1;
            if (++i < n && !(str[i] >= '0' && str[i] <= '9')) return 0;//正负号后面没数字
        }
        else if (str[i] >= '0' && str[i] <= '9') ;
        else return 0; //第一个有效字符不是'+','-',数字
        
        long res = 0;//结果
        int maxVal = INT_MAX;//边界值
        for (; i < n; ++i) {
    
    //初始i一定停在第一个数字上
            if (str[i] >= '0' && str[i] <= '9') {
    
    
                res = res * 10 + (str[i] - '0');
                if (res > maxVal) {
    
    //我们跳过了符号,都是按正数算的,最后再考虑正负号
                    if (symbol == 0 || symbol == 1) return INT_MAX;//没出现+-号就默认按正数算
                    else return INT_MIN;
                } 
            }
            else break;//出现数字以外的其他字符就停止
        }

        return (symbol == 0 || symbol == 1) ? res : (-1) * res;//没出界的int值,根据符号输出正数/负数
    }
};
  • Summary:
    atoi and stoi: the difference lies in the parameters, stoi parameter is string, atoi is const char*, but both can be converted to int, long, long long, just change to i, l, ll.

Guess you like

Origin blog.csdn.net/jiuri1005/article/details/114496773