Leetcode_String to Integer (atoi)

来源:互联网 发布:cydia网络错误 编辑:程序博客网 时间:2024/06/05 02:56

主要注意分析几种特殊的输入:

1 不规则的输入,但是有效:"-3924x8fc","+432"

2 无效格式,"++c","++1"

3 数据溢出

其中数据溢出的判断:

To deal with overflow, inspect the current number before multiplication. If the current number is greater than 214748364, we know it is going to overflow. On the other hand, if the current number is equal to 214748364, we know that it will overflow only when the current digit is greater than or equal to 8.

就是判断当前的数据时候已经大于INT_MAX的十分之一,是则溢出;或者,当前数据等于INT_MAX的十分之一,则需要判断此时再加进去的字符数据是否大于INT_MAX的最后一位。

class Solution {public:    int atoi(const char *str) {const int n=strlen(str);int i=0;int sign=1;while(str[i]==' '&&i<n)++i;if(str[i]=='+'){++i;}else if(str[i]=='-'){sign=-1;++i;}int num=0;for(;i<n;++i){if(str[i]<'0'||str[i]>'9')break;if(num>INT_MAX||(num==INT_MAX/10&&(str[i]-'0')>INT_MAX%10))//判断是否会产生溢出{return sign==1?INT_MAX:INT_MIN;}num=num*10+str[i]-'0';}return num*sign;           }};
方法二:直接用streamstring即可转换数据类型

class Solution {public:    int atoi(const char *str) {stringstream stream;stream<<str;int num;stream>>num;return num;            }};



0 0
原创粉丝点击