《剑指offer》第六十七题:把字符串转换成整数
// 面试题67:把字符串转换成整数 // 题目:请你写一个函数StrToInt,实现把字符串转换成整数这个功能。当然,不 // 能使用atoi或者其他类似的库函数。 #include <cstdio> long long StrToIntCore(const char* str, bool minus); enum Status { kValid = 0, kInvalid }; int g_nStatus = kValid; int StrToInt(const char* str) { long long num = 0; g_nStatus = kInvalid; if (str != nullptr && *str != '\0') //处理字符串为空指针或"" { bool minus = false; //负号标志 if (*str == '+') ++str; else if (*str == '-') { ++str; minus = true; } if (*str != '\0') //处理单符号问题 num = StrToIntCore(str, minus); } return (int)num; } long long StrToIntCore(const char* digit, bool minus) { long long num = 0; while (*digit != '\0') { if (*digit >= '0' && *digit <= '9') { int flag = minus ? -1 : 1; num = num * 10 + flag * (*digit - '0'); if ((!minus && num > 0x7FFFFFFF) //溢出 || (minus && num < (signed int)0x80000000)) { num = 0; break; } ++digit; } else //无效字符串 { num = 0; break; } } if (*digit == '\0') g_nStatus = kValid; return num; }
// ====================测试代码==================== void Test(const char* string) { int result = StrToInt(string); if (result == 0 && g_nStatus == kInvalid) printf("the input %s is invalid.\n", string); else printf("number for %s is: %d.\n", string, result); } int main(int argc, char* argv[]) { Test(nullptr); Test(""); Test("123"); Test("+123"); Test("-123"); Test("1a33"); Test("+0"); Test("-0"); //有效的最大正整数, 0x7FFFFFFF Test("+2147483647"); Test("-2147483647"); Test("+2147483648"); //有效的最小负整数, 0x80000000 Test("-2147483648"); Test("+2147483649"); Test("-2147483649"); Test("+"); Test("-"); return 0; }
分析:考虑各种意外输入。
class Solution { public: enum Status { kValid = 0, kInvalid }; int g_nStatus = kValid; int StrToInt(string str) { long long num = 0; g_nStatus = kInvalid; int length = str.length(); if (!str.empty()) { int current = 0; bool minus = false; if (str[current] == '+') ++current; else if (str[current] == '-') { ++current; minus = true; } if (current != length) num = StrToInt(str, current, minus); } return (int)num; } long long StrToInt(string digit, int current, bool minus) { long long num = 0; int length = digit.length(); int i = 0; for (i = current; i < length; ++i) { if (digit[i] <= '9' && digit[i] >= '0') { int flag = minus? -1 : 1; num = num * 10 + flag *(digit[i] - '0'); if ((!minus && num > 0x7FFFFFFF) || (minus && num < (signed int)0x80000000)) { num = 0; break; } } else { num = 0; break; } } if (i == length) g_nStatus = kValid; return num; } };