题目描述
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
输入描述:
输出描述
示例1:
输入:
+2147483647
1a33
输出:
解题思路
题意要求给的字符串必须满足以下要求:
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| class Solution { public: enum Status {kValia = 0, kInValia}; int g_nStatus = kValia; int StrToInt(string str) { long long num = 0; const char* cstr = str.c_str(); if (cstr != NULL && *cstr != '\0') { bool minus = false; if (*cstr == '+') cstr++; else if (*cstr == '-') { minus = true; cstr++; } if (*cstr != '\0') num = StrToIntCore(cstr, minus); } return (int)num; } long long StrToIntCore(const char* cstr, bool minus) { long long num = 0; while (*cstr != '\0') { if (*cstr >= '0' && *cstr <= '9') { int flag = minus ? -1 : 1; num = num * 10 + flag * (*cstr - '0'); if ((!minus && num > 0x7fffffff) || (minus && num < (signed int)0x80000000)) { num = 0; break; } cstr++; } else { num = 0; break; } } if (*cstr == '\0') g_nStatus = kValia; return num; } };
|
但是,在牛客上不能通过,测试用例为:-2147483649超出 int 的取值范围。
参考博文链接:https://cuijiahua.com/blog/2018/01/basis_49.html
https://www.nowcoder.com/questionTerminal/1277c681251b4372bdef344468e4f26e?f=discussion