LeetCode Algorithms 8. String to Integer (atoi) 题解

来源:互联网 发布:js表格分页插件 编辑:程序博客网 时间:2024/06/05 15:40

题目
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.

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.

这是一个用自己的方法实现atoi的题目,不看实现要求的话,这是一个很考验的题目,需要自己去测试边界。

看了要求之后,可以总结为几点:
1. 出现在数字字符串前面的‘ ’空格需要忽略,以[0-9]或者正负号开始(连续两个正负号不能算构成数字)
2. 出现在数字字符串后面的字符需要忽略
3. 如果首个非空格的字符不能构成数字字符串,则不能转换成数字
4. 如果不能转换成数字,返回0,如果转换成数字后超出范围,返回边界值(INT_MAX || INT_MIN

这样就清晰许多了,设置一个index,从头开始遍历字符串,先用while循环把空格跳过,然后如果遇到正负号,设置一个正负标志记录下来,然后判断是否是数字字符,然后转换为整型类型,遇到非数字字符则跳出循环。

转换为整型的时候,可以让res=res*10+digit,这样一次遍历就能完成转换。题目还有个边界要求,如果使用int型,储存不了比INT_MAX更大的数(或比INT_MIN更小),所以使用signed long long型变量去储存计算结果(测试集里面有long long型的边界值,故使用更大的整型类型),然后与边界值比较。不过这样做会增大内存消耗,能否仍然使用int类型的变量呢,答案是可以的,因为使用int型储存时,超过最大值会溢出,然后值就会改变,又由于计算结果时是有进位操作(*10),如果计算后再退位(/10)的结果与进位前一样,那么可以判定没有超出范围。
代码如下:

int myAtoi(string str) {    if (str.empty() || str == "") return 0;    bool nagetive = false;    int i = 0;    int res = 0;    while (str[i] == ' ') {        i++;    }    if (str[i] == '-' || str[i] == '+') {        nagetive = str[i++] == '-' ? true : false;    }    while (isdigit(str[i])) {        int oldres = res;        res = res * 10 + (str[i++] - '0');        //if (res > INT_MAX && !nagetive) return INT_MAX;        //if (res > INT_MAX && nagetive) return INT_MIN;        if (res / 10 != oldres) {            return nagetive ? INT_MIN : INT_MAX;        }    }    return nagetive ? 0 - res : res;}
0 0
原创粉丝点击