#include <iostream>
#include <string>
int myAtoi(std::string str) {
int sign = 1, base = 0, i = 0;
// skip leading whitespaces
while (str[i] == ' ') {
i++;
}
// check for sign
if (str[i] == '-' || str[i] == '+') {
sign = (str[i++] == '-') ? -1 : 1;
}
// convert digits to integer
while (isdigit(str[i])) {
if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) {
return (sign == 1) ? INT_MAX : INT_MIN;
}
base = 10 * base + (str[i++] - '0');
}
return base * sign;
}
int main() {
std::string str = "12345";
int result = myAtoi(str);
std::cout << "Converted integer: " << result << std::endl;
return 0;
}
这段代码实现了一个简单的atoi函数,可以将字符串转换为整数。注意在实现时需要考虑一些边界条件,比如正负号、溢出等情况。
网友留言: