String to Integer (atoi)

来源:互联网 发布:macbookpro必装软件 编辑:程序博客网 时间:2024/04/30 12:31

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.

解析:基本的要求

(1)一开始先找到不是空格的第一个字符

(2)如果这个字符为‘+’或者‘-’,相应的符号设置为正和负。

(3)接下来就只能是数字(不能有两个符号“+-2结果也是0”),如果不是数字就退出,返回当前所计算得到的值。

(4)如果这个值上溢,则返回整数的最大值,如果这个值下溢,则返回整数的最小值。因此存储的时候要用long

(5)空字符也返回0。


#include <iostream>using namespace std;int myatoi(const char *str) {const char *p = str;long long res = 0;int sign = 1;bool flag = false;while(*p!='\0'&&*p == ' '){p++;}while(*p != '\0'&&*p!='.'){if(*p == '-'){if(flag == true)return res*sign;flag = true;sign = -1;p++;continue;}if(*p == '+'){if(flag == true)return res*sign;flag = true;sign = 1;p++;continue;}if( *p >='0' && *p <= '9'){res = res*10 + (*p - '0');if(res*sign >INT_MAX)return INT_MAX;if(res*sign < INT_MIN)return INT_MIN;p++;}else{return res*sign;}}res = res*sign;return res;}int main(void){char *str = "   -12   34";cout << myatoi(str) << endl;cout << "====================" << endl;cout << atoi(str) << endl;system("pause");return 0;}



0 0
原创粉丝点击