class Solution { public: int myAtoi(string str) { if (str.empty()) { return 0; } int result = 0; int current_position = 0; //current position 永遠指向下一個要讀取的字符 bool sig_set = false; bool number_set = false; bool is_negative = false; //stage 1 while (sig_set == false && number_set == false && current_position < str.size()) { if (str[current_position] == ' ') { current_position++; } else if (str[current_position] == '+' || str[current_position] == '-') { sig_set = true; if (str[current_position] == '-') { is_negative = true; } current_position++; } else if (str[current_position] >= '0' && str[current_position] <= '9') { number_set = true; result = result * 10 + (str[current_position] - '0'); //should not be overflowed here current_position++; } else { return result; } } //stage 2 這個階段有可能不執行 while (number_set == false && current_position < str.size()) { if (str[current_position] == ' ') { current_position++; } else if (str[current_position] >= '0' && str[current_position] <= '9') { number_set = true; result = result * 10 + (str[current_position] - '0'); //should not be overflowed here current_position++; } else { return result; } } while (current_position < str.size()) { if (str[current_position] >= '0' && str[current_position] <= '9') { number_set = true; int a = str[current_position] - '0'; if ((INT_MAX - a) / 10 < result) { if (is_negative) { return INT_MIN; }else{ return INT_MAX; } } result = result * 10 + str[current_position] - '0'; current_position++; } else { break; } } if (is_negative) { return -result; }else{ return result; } } };