-
int c; long total; int sign; while ( isspace((int)(unsigned char)*nptr) ) ++nptr; c = (int)(unsigned char)*nptr++; sign = c; if (c == ''-'' || c == ''+'') c = (int)(unsigned char)*nptr++; total = 0; while (isdigit(c)) { total = 10 * total + (c - ''0''); c = (int)(unsigned char)*nptr++; } if (sign == ''-'') return -total; else return total;
需要注意的问题(摘自剑指offer)
面试官至少会期待应聘都能够在不需要提示的情况下,考虑到输入的字符串中有非数字字符和正负号,要考虑到最大的正整数和最小的负整数以及溢出。同时面试试还期待应聘者能够考虑到当输入的字符串不能转换成整数时,应该如何做错误处理。
1、检查字符串是否为空
2、对非法输入,返回0,并设置全局变量
3、溢出
4、空字符串""
5、输入字符串只有"+"或"-"号