通知短信+运营短信,5秒速达,支持群发助手一键发送🚀高效触达和通知客户 广告
**一. 题目描述** 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. 异常字符出现(按照atoi函数的规定是,把异常字符起的后面全部截去,保留前面的部分作为结果); 2. 数字越界(返回最接近的整数); 3. 字符串结束。 **三. 示例代码** 只要注意边界问题,编程没有太大难度,由于时间有限,先借鉴了别人的程序。 ~~~ #include <iostream> using namespace std; // 时间复杂度O(n),空间复杂度O(1) class Solution { public: int atoi(const char *str) { int num = 0; int sign = 1; // 正负数标记 int strSize = strlen(str); int index = 0; while (str[index] == ' ' && index < strSize) index++; if (str[index] == '+') ++index; else if (str[index] == '-') { sign = -1; ++index; } for (; index < strSize; ++index) { if (str[index] < '0' || str[index] > '9') break; // 以下操作检查是否溢出 if (num > INT_MAX / 10 || ((num == INT_MAX / 10) && (str[index] - '0') > (INT_MAX % 10))) return sign == -1 ? INT_MIN : INT_MAX; num = num * 10 + str[index] - '0'; } return num * sign; } }; ~~~ ![](https://box.kancloud.cn/2016-01-05_568bb5ef2471b.jpg) **四. 小结** 面试中还是经常出现这种问题的,对应的有整数转字符串。这类问题中考虑好边界条件是关键。