8. String to Integer (atoi)

来源:互联网 发布:高考文言文阅读 知乎 编辑:程序博客网 时间:2024/05/16 04:17

题目:String to Integer (atoi)

原题链接:https://leetcode.com/problems/string-to-integer-atoi/
Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

spoilers alert… click to show requirements for atoi.

Requirements for atoi:
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.

设计字符串转整数的算法,要求注意到所有可能的情况。

首先这个函数需要考虑到字符串最前面的一些空格,这些空格没有实际作用,但是它们并不影响字符串的合法性,因此,在转换的过程中第一步需要把前面的空格给去掉。
其次,字符串是允许在数字的最前面有正负号的,所以在去掉空格之后还需要判断一下第一位是不是正负号;
接着判断完正负号之后开始把剩余的部分进行转换,由于可能存在超出32位 INT 表示范围的情况,所以要留心判断当前累计的数是否已经超限(这一步可以初步判断一下绝对值是不是超过2147483648);
在累计字符串的数字的过程中如果遇到了其他字符(包括空格),这个时候就直接停止累计,后面的字符无论有没有数字都不在记录在内。
最后输出的时候判断一下是否超过2147483647或者小于-2147483648.

代码如下:

class Solution {public:    int myAtoi(string str) {        if(!str.length()) return 0;        bool flag = false;        int i = 0;        while(str[i] == ' ') i++;        str = str.substr(i, str.length() - i);        if(str[0] == '+' || str[0] == '-') {            if(str[0] == '-') flag = true;            str = str.substr(1, str.length() - 1);        }        int len = str.length();        long long ret = 0;        for(int i = 0; i < len; ++i) {            if(ret > 2147483648) break;            if(str[i] >= '0' && str[i] <= '9') ret = ret * 10 + (str[i] - '0');            else break;        }        if(flag) {            ret = -ret;            return ret < INT_MIN ? -2147483648 : ret;        }else{            return ret > INT_MAX ? 2147483647 : ret;        }    }};
0 0