[C++]LeetCode: 24 String to Integer (atoi)

来源:互联网 发布:js require函数的用法 编辑:程序博客网 时间:2024/04/29 22: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.

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.

题目要求:实现字符串到数字的转换;忽略第一个合法字符前的所有空格,从符号读取,直到合法数字结束,合法数字之后的字符一并忽略。如果没有合法转换字符,返回0,如果超出范围,返回INT_MAX OR INT_MIN.

思路:按照规则读取所有的合法输入,并且读取过程中检查是否overflow

解决四点问题:

1. 处理所有的开头的空格

2. 确定数字的符号

3. 溢出

4. 非法输入

Attention: 

1. 字符转数字,字符存储的是ASCII码,用ASCII码-48('0'的ASCII码)就得到对应的数字。ASCII码: 32~126(共95个)是字符(32是空格),其中48~57为0到9十个阿拉伯数字.

2. 确定符号的方法很巧妙.  " sign = 1 - 2 * (str[i++] == '-'); "

3. 判断溢出,INT_MAX表示有符号整数最大表示数字,需要截取尾部,判断尾部。注意判断条件。

4. 只统计ASCII码在'0' 和'9'之间的字符,直接就屏蔽了非法输入。所以一定要初始化digit 和sign,非法输入返回0.

算法复杂度:O(N)

AC Code:

class Solution {public:    int atoi(const char *str) {        //实现字符串到数字的转换        //忽略第一个合法字符前的所有空格,从符号读取,直到合法数字结束,合法数字之后的字符一并忽略。如果没有合法转换字符,返回0,如果超出范围,返回INT_MAX OR INT_MIN.        //思路:按照规则读取所有的合法输入,并且读取过程中检查是否overflow        //Attention: 字符转数字,字符存储的是ASCII码,用ASCII码-48('0'的ASCII码)就得到对应的数字。                 //需要制定初值,如果输入不带负号,表示是正数。如"1"        int digit = 0, sign = 1, i = 0;                while(str[i] == ' ')        {   i++; }                //确定符号的方法很巧妙,利用了对偶的性质; str[i++]先判断str[i]是否是负号,再i++        if(str[i] == '+' || str[i] == '-')        {   sign = 1 - 2 * (str[i++] == '-'); }                while(str[i] >= '0' && str[i] <= '9')        {            //Because INT_MAX has been divided by 10, so the tail vanishes. if the tail is 8 or 9, it will overflow.            //关键点!!!! str[i]得到的是字符的ASCII码,减去0得到对应的数字,字符转数字的方法 '0'的ASCII码是48.48~57表示阿拉伯0~9.            if(digit > INT_MAX / 10 || (digit == INT_MAX / 10 && str[i] - '0' > 7))            {                if(sign == 1)                    return INT_MAX;                else                    return INT_MIN;            }            digit = digit * 10 + (str[i++] - '0');        }        return digit * sign;      }};




0 0
原创粉丝点击