题目要求:
输入一个表示整数的字符串,把该字符串转换成整数并输出。
例如:输入字符串"235",输出整数235.
参考资料:剑指offer第49题、程序员编程艺术 (by July)
题目分析:
1.基本思路:
int StrToInt(char *str)
{int num = 0;while(*str != '\0'){num = num*10+*str-'0';str++;}return num;
}
2.考虑各种测试用例都能有正确输出:
-
- 输入为NULL
- 输入为非数字
- 输入为""
- 输入表示的整数溢出
- 输入正负数
- 输入+0/-0
代码实现:
剑指offer源码:
// 《剑指Offer——名企面试官精讲典型编程题》代码
// 著作权所有者:何海涛
#include
#include
//输入为""和"0",都是return 0;则通过全局变量可以进行区分(""是无效的,"0"有效)。
int g_nStatus = kValid;int StrToInt(const char* str)
{g_nStatus = kInvalid;int num = 0;if(str != NULL && *str != '\0') {bool minus = false;if(*str == '+')str ++;else if(*str == '-') {str ++;minus = true;}//加一个判断可以使得"+"和"-"直接return 0,且全局变量表示无效;if(*str != '\0') {num = StrToIntCore(str, minus);}}return num;
}int StrToIntCore(const char* digit, bool minus)
{//用long long避免num溢出long long num &#61; 0;while(*digit !&#61; &#39;\0&#39;) {if(*digit >&#61; &#39;0&#39; && *digit <&#61; &#39;9&#39;) {int flag &#61; minus ? -1 : 1;num &#61; num * 10 &#43; flag * (*digit - &#39;0&#39;);if((!minus && num > 0x7FFFFFFF) || (minus && num <(signed int)0x80000000)){num &#61; 0;break;}digit&#43;&#43;;}else {num &#61; 0;break;}}if(*digit &#61;&#61; &#39;\0&#39;) {g_nStatus &#61; kValid;}return num;
}// &#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;测试代码&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;&#61;
void Test(char* string)
{int result &#61; StrToInt(string);if(result &#61;&#61; 0 && g_nStatus &#61;&#61; kInvalid)printf("the input %s is invalid.\n", string);elseprintf("number for %s is: %d.\n", string, result);
}int main(void)
{Test(NULL);Test("");Test("123");Test("&#43;123");Test("-123");Test("1a33");Test("&#43;0");Test("-0");//有效的最大正整数, 0x7FFFFFFFTest("&#43;2147483647"); Test("-2147483647");Test("&#43;2147483648");//有效的最小负整数, 0x80000000Test("-2147483648"); Test("&#43;2147483649");Test("-2147483649");Test("&#43;");Test("-");return 0;
}