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.
题目只考虑了" 123"或者"+123","-123",而不考虑"abs123"等情况,所以一开始只要排除空格,然后直接判断正负号,接着读取数字字符即可。
但是要考虑溢出,int占四个字节,32位,取值范围是-2147483648~2147483647;
若超过了负数则 输出-2147483648 超过了正数则输出2147483647
在科普一个知识点,倘若某个数超过了2147483647则会变为负数,反过来一样
int myAtoi(char *str) { while(*str == 32) str++; if((*str != '-' && *str != '+') && (*str < '0' || *str >'9')) return 0; int t = 1; long long result = 0; if(*str == '-'){ t = -1; str++; }else if(*str == '+'){ str++; } while(*str >= '0' && *str <= '9'){ result = result*10 + (*str - '0'); if(t == -1 && result >= 2147483648){ result = 2147483648; break; } if(result > 2147483647){ result = 2147483647; break; } str++; } result *= t; return result; }