标签:integer string atoi leetcode
String to Integer (atoi) : https://leetcode.com/problems/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.
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”, “-0”, “0”, 都应返回 0
“ +123”,”+123”, “123” ,”123ab123” 都应返回123
“-123”,返回 -123
“”, “+”, “-“, “abc”,”+-1”,”~2”,等 应返回0
以及溢出:
“2147483648“返回 INT_MAX (2147483647)
“-21474836480”返回 INT_MIN (-2147483648)
需要注意的是,如何区分正确的0和错误字符返回的0:
定义一个全局变量,用来标记错误的0
int g_error = 0;
int myAtoi(char* strl) {
if (strl == NULL) {
g_error = -1;
return 0;
}
// 跳过空格
while (*strl != ‘\0‘ && *strl == ‘ ‘) {
strl++;
}
int sign = 0; // 符号位,负数为1,正数为0
if ((strl[0] == ‘+‘ || strl[0] == ‘-‘) && strl[1] == ‘\0‘) {
g_error = -2;
return 0;
} else if (strl[0] == ‘+‘) {
sign = 0;
strl++;
} else if (strl[0] == ‘-‘) {
sign = 1;
strl++;
}
long result = 0;
for (; *strl != ‘\0‘; strl++) {
int num = *strl- ‘0‘;
if (num < 0 || num > 9) {
break;
} else {
result = result*10 + num;
// 处理溢出
if (sign && (result > INT_MAX)) {
g_error = -3;
return INT_MIN;
}
if (!sign && (result > INT_MAX)) {
g_error = -3;
return INT_MAX;
}
}
}
return sign ? -result : result;
}
leetcode | String to Integer (atoi)
标签:integer string atoi leetcode
原文地址:http://blog.csdn.net/quzhongxin/article/details/46494307