String to Integer(atoi)
atoi()函数将C类型的字符串转换为int值。
1.忽略字符串开头的空格直至遇到非空格字符
2.字符串的开头可以有'+'或者'-',正号或负号后接十进制数字
3.所有数字后面的非法字符都将被忽略,且对函数功能不产生任何影响
4.如果第一个非空格序列非法或者字符串为空或者只有空格,则不进行任何转换并返回0值
5.当输入的字符串表示的数值溢出时,返回INT_MAX(2147483647)或者INT_MIN(-2147483648)
下面是顺着思路想的一种解法,代码不是很简洁,但是显示地判断了空串和全是空格的情况。如果第一个非空格字符不是整数符号或者数字,则不会执行while(str[i]>='0'&&str[i]<='9')循环,直接返回0。
将result设置为long long类型是为了可以将更长的数字字符串转化为整型,long long为64位整型。
class Solution { public: int myAtoi(string str) { long long result=0; int flag=1; int i=0; while(i<str.size()&&str[i]==' ') i++; if(i==str.size()) return 0; if(str[i]=='-'||str[i]=='+') { flag=(str[i]=='-')?-1:1; i++; } while(str[i]>='0'&&str[i]<='9') { result=result*10+str[i]-'0'; if(result*flag>=INT_MAX) return INT_MAX; if(result*flag<=INT_MIN) return INT_MIN; i++; } return result*flag; } };
可以不显式地判断字符串为空或者全是空格的字符串,并且可以使用库函数来完成某些操作,代码如下:
class Solution { public: int myAtoi(string str) { long long result=0; int flag=1; int pos=str.find_first_not_of(' '); if(str[pos]=='-'||str[pos]=='+') { flag=(str[pos]=='-')?-1:1; pos++; } while(isdigit(str[pos])) { result=result*10+str[pos]-'0'; if(result*flag>=INT_MAX) return INT_MAX; if(result*flag<=INT_MIN) return INT_MIN; pos++; } return result*flag; } };
find_first_not_of()是string类下的函数,在这里是找到str中第一个不是空格的字符位置并返回,返回的是字符在数组中的位置(即0...N)。
isdigit()是判断某字符是否为数字字符。使用时 #include <cctype>
以上两种方法,只是完成leetcode中的题目的解法。在实际面试中,面试官可能还要考察你对非法输入的处理。同样是return 0,有可能是正常返回"0"值,或者是遇到非法输入从而返回0。
(剑指offer中第49题)