困难 转换字符串到整数
15%
通过
实现atoi这个函数,将一个字符串转换为整数。如果没有合法的整数,返回0。如果整数超出了32位整数的范围,返回INT_MAX(2147483647)如果是正整数,或者INT_MIN(-2147483648)如果是负整数。
您在真实的面试中是否遇到过这个题?
Yes
样例
"10" =>10
"-1" => -1
"123123123123123" => 2147483647
"1.0" => 1
class Solution {
public:
/**
* @param str: A string
* @return An integer
*/
int atoi(string str) {
// write your code here
int len = str.size();
if (len == 0) {
return 0;
}
long long res = 0;
int start = 0;
while (str[start] == ' ' || str[start] == '0') {
++start;
}
bool isneg = 0;
if(str[start] == '+') {
++start;
}
else if (str[start] == '-') {
isneg = 1;
++start;
}
while (start < len) {
if(str[start] > '9' || str[start] < '0') {
break;
}
res = res* 10 + (str[start] - '0');
if (res > INT_MAX) {
if(isneg) {
return INT_MIN;
} else {
return INT_MAX;
}
}
++start;
}
if (isneg) {
return -res;
}
return res;
}
};