class Solution { public: int myAtoi(string str) { if (str == "") return 0; //判断是否为空 int i = 0, sign = 1; long long sum = 0; //用long long来存结果,易于判断是否溢出,用int的话比较麻烦 while (str[i] == ' ') i++; //忽略前置的空格 //判断是否溢出,溢出的话根据sign判断返回最小值还是最大值,这里体现了用longlong的好处 if (str[i] == '+' || str[i] == '-') sign = 44 - str[i++]; for (i; i < str.length(); i++) { if (str[i] >= '0' && str[i] <= '9') sum = sum * 10 + str[i] - '0'; else break; //判断是否溢出,溢出的话根据sign判断返回最小值还是最大值,这里体现了用longlong的好处 if (sum > INT_MAX) return sign == -1 ? INT_MIN : INT_MAX; } return sum * sign; } };