8 String to Integer (atoi)
int myAtoi(string str) {
// rid of spaces
int integral_start = 0;
while (str[integral_start] == ' ') integral_start++;
// a sign or digit must come next
if (!(isdigit(str[integral_start]) || str[integral_start] == '-' || str[integral_start] == '+'))
return 0;
// obtain sign (if any) - assume positive
bool is_pos = str[integral_start] == '-' ? false : true;
bool has_sign = str[integral_start] == '-' || str[integral_start] == '+';
// must be a digit after sign
if (has_sign) {
integral_start++;
if (integral_start >= str.size() || !(isdigit(str[integral_start]))) return false;
}
// obtain all digits that come next
int integral_end = integral_start;
while (integral_end < str.size() && isdigit(str[integral_end])) integral_end++;
integral_end--;
// form the result - everything after becomes discarded
long long int result = 0;
long long int base_mult = 1;
for (int i = integral_end; i >= integral_start; i--) {
result += (str[i] - '0') * base_mult;
base_mult *= 10;
}
return is_pos ? result : -1 * result;
}Last updated