Subject description:
(Integer.valueOf achieve returns 0 (string) function, but the string does not meet the requirements of the digital) converting a string to an integer, the request can not use the library function converts the integer string. Value of 0 or a character string is not a valid value of 0 is returned.
Ideas: The main question investigated thinking rigor, note the following:
(1) whether an empty string pointer, string length is 0;
(2) Consider the positive and negative string, to be considered in particular is a positive number with or without a positive number;
(3) ensure that all except the sign bit characters are few characters must be between 0 and 9, and 0 otherwise.
class Solution {
public:
int StrToInt(string str) {
int len = str.length();
if(len == 0)
return 0;
int s = (str[0] == '-' ? -1:1); //记录符号正负
int i = ((str[0] == '-')||(str[0] == '+')?1:0); //看字符串前有符号没有
long long result = 0;
for(;i<len;i++){
if(str[i]>='0' && str[i]<='9') //只有每一个单个字符都在0~9之间才合理,否则返回0
result = result*10 + str[i]-'0';
else
return 0;
}
return result*s; //乘以符号位
}
};