atoi (String to Integer) leetcode
将字符串转化为数字,其注意事项有:
Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.(出现数字之后的字母直接忽略并结束,哪怕后面还有数字)
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
#include<iostream> #include<string> #include<cmath> //#include<limits> using namespace std; class Solution { public: int myAtoi(string str) { long long tes, res = 0; int sign = 1, count = 0; bool flag = false; int len = str.length(); for (int i = 0; i < len; ++i) { //首先就是去除最前面连续着的所有空格 if (str[i] == ' '&&flag == false) continue; else flag = true; //符号不能+-都出现 if (str[i] == '+' || str[i] == '-') count++; //最后的结果的正负 if (str[i] == '-') { sign = -1; } //一旦中间遇到字母或者空格就结束了 if (str[i] >= 'a'&&str[i] <= 'z' || str[i] >= 'A'&&str[i] <= 'z' || str[i] == ' ') break; //真正干活的,将字符形式的数字转化为真正的数字 if (str[i] >= '0'&&str[i] <= '9') { int s = str[i] - '0'; res = res * 10 + s; tes = res*sign; if (tes > INT_MAX) return INT_MAX; else if (tes < INT_MIN) return INT_MIN; } } if (count>1) return 0; return sign*res; } }; int main() { Solution test; string s1 = "2222147483647"; string s2 = " -11919730356x"; int result = test.myAtoi(s1); cout << result << endl; result = test.myAtoi(s2); cout << result << endl; //long long temp = 2147483647; //int r = temp; //cout << r; ////long long temp=-12345678901; ////if (temp < (long long)INT_MIN) //// cout << INT_MIN; return 0; }