backup = sum;
sum = sum * 10 + ans;
if (sum < 0 || backup != (sum - ans) / 10) {
return sign > 0 ? INT_MAX : INT_MIN;
}
class Solution {
public:
int myAtoi(string str) {
if (str.empty()) {
return 0;
}
int size = str.length(), i = 0, sign = 1, sum = 0, backup = 0;
//如果碰到空白就往後移
while (i < size && str[i] == ' ') {
i++;
}
//判斷符號
if (str[i] == '+') {
sign = 1;
i++;
} else if (str[i] == '-') {
sign = -1;
i++;
}
while (i < size && isdigit(str[i])) {
int ans = int(str[i] - '0');
backup = sum;
sum = sum * 10 + ans;
if (sum < 0 || backup != (sum - ans) / 10) {
return sign > 0 ? INT_MAX : INT_MIN;
}
i++;
}
return sum * sign;
}
};