题目:https://leetcode.com/problems/string-to-integer-atoi/
Implement atoi to convert a string to an integer.
思路:
把情况搞清楚就好了。
代码:C++:
int myAtoi(string str) {//这个代码思路比较乱 int solve = 0; int coe = 1; bool find_sign = false; bool find_num = false; for (int i = 0; i < str.length(); i++) { if (isspace(str[i])){ if (find_num || find_sign) break; continue; } if (str[i] == '+'){ if (find_sign) return 0; find_sign = true; continue; } else if (str[i] == '-'){ if (find_sign) return 0; find_sign = true; coe = -1; continue; } if (isdigit(str[i])){ find_sign = true; find_num = true; int temp = 10 * solve + (str[i] - '0'); if (temp / 10 != solve) return coe == 1 ? INT_MAX : INT_MIN; solve = temp; continue; } break;//meet other ASCII code } solve *= coe; return solve; }