- 字符串转换整数 (atoi)
https://leetcode.cn/problems/string-to-integer-atoi/description/
请你来实现一个 myAtoi(string s) 函数,使其能将字符串转换成一个 32 位有符号整数。
函数 myAtoi(string s) 的算法如下:
空格:读入字符串并丢弃无用的前导空格(" ")
符号:检查下一个字符(假设还未到字符末尾)为 ‘-’ 还是 ‘+’。如果两者都不存在,则假定结果为正。
转换:通过跳过前置零来读取该整数,直到遇到非数字字符或到达字符串的结尾。如果没有读取数字,则结果为0。
舍入:如果整数数超过 32 位有符号整数范围 [−231, 231 − 1] ,需要截断这个整数,使其保持在这个范围内。具体来说,小于 −231 的整数应该被舍入为 −231 ,大于 231 − 1 的整数应该被舍入为 231 − 1 。
返回整数作为最终结果。

class Solution {
public:
int myAtoi(string s) {
int s_len = s.size();
int cur_idx = 0;
int sf = 1; // 符号
while (cur_idx < s_len) {
if (s[cur_idx] == ' ') {
cur_idx++;
} else {
break;
}
}
if (s[cur_idx] == '+') {
sf = 1;
} else if (s[cur_idx] == '-') {
sf = -1;
} else {
cur_idx--;
}
cur_idx++;
while (cur_idx < s_len) {
if (s[cur_idx] == '0') {
cur_idx++;
} else {
break;
}
}
long long num = 0;
int MAX_INT_LENGTH = 12;
int start_idx = cur_idx;
while (cur_idx < s_len && cur_idx - start_idx < MAX_INT_LENGTH) {
if (s[cur_idx] >= '0' && s[cur_idx] <= '9') {
num = num * 10 + s[cur_idx] - '0';
cur_idx++;
} else {
break;
}
}
num = num * sf;
int MAX_INT = 0x7FFFFFFF;
int MIN_INT = MAX_INT * -1 - 1;
if (num >= MAX_INT) {
return MAX_INT;
} else if (num <= MIN_INT) {
return MIN_INT;
}
int ans = num;
return ans;
}
};
1512

被折叠的 条评论
为什么被折叠?



