7. String to Integer (atoi) FROM Leetcode

题目

Implement atoi to convert a string to an integer.

频度: 5

解题之法

class Solution {
public:
int myAtoi(string str) {
    long result = 0;
    int indicator = 1;
    int length = str.size();
    if(length>0)
    {
    for(int i = 0; i<length;)
    {
        // 使用find_first_not_of需要 #include <string>;
        i = str.find_first_not_of(' ');
        if(str[i] == '-' || str[i] == '+')
            indicator = (str[i++] == '-')? -1 : 1;
        while('0'<= str[i] && str[i] <= '9') 
        {
            result = result*10 + (str[i++]-'0');
            // 使用INT_MAX 需要 #include <climits>;
            if(result*indicator >= INT_MAX) return INT_MAX;
            if(result*indicator <= INT_MIN) return INT_MIN;                
        }
        return result*indicator;
    }
        
    }else{
        return 0;
    }
}
};

分析

atoi函数是输出一个字符串中的第一个数字串,其余的部分忽略。

需要考虑以下几种情况:

  • discards all leading whitespaces
  • sign of the number
  • overflow
  • invalid input

完整描述如下:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容