Topic:
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please don't see below and ask yourself what is the possible input cases.
notes: it is intended for the problem to be specified Vaguely (ie, no given input specs). You is responsible to gather all the input requirements up front.
update (2015-02-10):
the signature of The c++ function had been updated. If you still see your function signature accepts A const char * argument, please click the reload Button to Reset your code definition.
Analysis: The problem of understanding on the waste of a kung fu, see a few times also did not grasp the essence. The topic is to convert string strings into integer data, similar to the Atoi function in C + + library, the key to solve this problem lies in two aspects: (1) The legal judgment of the string format (2) The overflow judgment of the conversion result first, for the string format, the space does not count into the calculation, Judging from the first non-null character, the first letter can only be one of the symbols (+,-) and the number; traversing a string from the beginning of the calculation to the last digit; second, for the result of the conversion, we know that the range of integer data is int_min (-2147482648) to Int_ Max (2147483647), out of range returns the maximum and minimum values. So we can start storing the result with a long long variable; AC code:
Class Solution {public: int myatoi (string str) {if (str.length () = = 0) return 0;//used to store the result long long result = 0; int sign = 1, i=0;while (str[i] = = ") {if (str[i] = =") i++;} if (str[i] = = ' + ') i++;else if (str[i] = = '-') {sign = -1;i++;} for (int j=i; j<str.length (); j + +) {if (str[j]>= ' 0 ' && str[j]<= ' 9 ') {result = result * + (str[j]-' 0 '); if (Result > Int_max) return sign<0? Int_min:int_max;} Elsebreak;} Result *= sign;return (int) result;} ;
Leetcode (8) String to Integer (atoi)