Implement atoi to convert a string to an integer.
Hint: carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: it is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
Analysis: Question input is a bit disgusting, and various input types are broken. The only value is that the int range of the out-of-range input is-231-231-1, that is, (-2147483648--2147483647 ).
When the number is 2147483647 + 1, it becomes-2147483648 in the computer. That is to say, this is a ring. when it crosses the border, it starts from the other end. Why?
Because the computer uses the complement code to represent all integers, and the highest bit is the symbol bit, the highest bit of a negative number is called negative weight.
-2147483648-231, that is, the highest bit is 1, and the rest are all 0.
2147483647 the highest bit of 231-1-1 is 0, and the rest are all 1.
The calculation process of-2147483648-1 is as follows:
Class solution {public: bool isvalid (char I, char next) {If (next = '-' | next = '+') return false; else return I = '-' | I = '+' | (I >='0' & I <= '9 ');} int atoi (const char * Str) {int max = ~ (Unsigned INT) 0/2; int min = MAX + 1; if (STR = NULL | STR = "") return 0; int Len = strlen (STR ); long long res = 0; int I = 0; while (STR [I] = '') ++ I; // ignore the start Space
If (isvalid (STR [I], STR [I + 1]) {// judgment symbol and continuous symbol switch (STR [I]) {Case '-': for (INT q = I + 1; q <Len; ++ q) {If (STR [Q]> = '0' & STR [Q] <= '9') RES = res * 10 + STR [Q]-'0 '; else break;} res =-res; If (RES <= min) return min; return res; Case '+': For (INT q = I + 1; q <Len; + q) {If (STR [Q]> = '0' & STR [Q] <= '9 ') res = res * 10 + STR [Q]-'0'; else break;} If (RES> = max) return Max; return res; default: for (INT q = I; q <Len; ++ q) {If (STR [Q]> = '0' & STR [Q] <= '9 ') res = res * 10 + STR [Q]-'0'; else break;} If (RES> = max) return Max; return res; break ;}} else return 0 ;}};
String to INTEGER (atoi)