Leetcode#8 atoi
Published:
Link:
https://leetcode.com/problems/string-to-integer-atoi/description/
Idea:
Overflow check
Solution:
class Solution {
public:
int myAtoi(string str) {
unsigned long long tmp = 0;
int i = 0;
bool triggered = false;
int y = 1;
while (i < str.size()) {
if (!triggered) {
if (str[i] == ' ') {
i++;
} else if (str[i] == '+' || str[i] == '-') {
triggered = true;
y = str[i] == '+' ? 1 : -1;
i++;
} else if ('0' <= str[i] && '9' >= str[i]) {
triggered = true;
tmp = tmp * 10 + str[i] - '0';
i++;
} else {
break;
}
} else {
/* triggered */
if ('0' <= str[i] && '9' >= str[i]) {
tmp = tmp * 10 + str[i] - '0';
i++;
if (tmp > (unsigned long long)INT_MAX) {
if (y > 0) {
return INT_MAX;
} else {
return INT_MIN;
}
}
} else {
break;
}
}
}
return tmp*y;
}
};