题解 | #把字符串转换成整数(atoi)#
把字符串转换成整数(atoi)
https://www.nowcoder.com/practice/d11471c3bf2d40f38b66bb12785df47f
#include <climits>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return int整型
*/
long long shuzi(long long num, char ch){
int last = ch - '0';
num = num * 10 + last;
return num;
}
int StrToInt(string s) {
// write code here
int num_index = 0;
int symbol_index = 1;
int symbol_num = 0;
long long num = 0;
for (auto ch : s){
if (ch == '-' || ch == '+'){
if(num_index == 0 && symbol_num == 0){
if (ch == '-')
symbol_index = -1;
symbol_num++;
}
else
return num * symbol_index;;
}
if (num_index == 1 && (ch < '0' || ch > '9' ) || isalpha(ch))
return num * symbol_index;
if (ch >= '0' && ch <= '9'){
num_index = 1;
num = shuzi(num, ch);
if (num > INT_MAX ){
if (symbol_index == 1)
return INT_MAX;
else
return INT_MIN;
}
}
}
int result = int(num);
return result * symbol_index;
}
};

