5. The string into an integer

Subject description:
(Integer.valueOf achieve returns 0 (string) function, but the string does not meet the requirements of the digital) converting a string to an integer, the request can not use the library function converts the integer string. Value of 0 or a character string is not a valid value of 0 is returned.
Enter a description:
Enter a string including alphanumeric symbols, can be null
Output Description:
If it is a legitimate expression of the digital value is returned, otherwise 0
Example 1
Entry
copy
+2147483647
    1a33
Export
copy
2147483647
    0
Idea: If the string can be converted to an integer in line with the meaning of the questions, then certainly it is a string of characters '0' - between '9', the symbol + or - if there is, then certainly the first occurrence of the string a position element, if there is somewhere in the middle of the string, the string can not be converted to digital .
Then there is: res = (res << 1) + (res << 3) + (str [i] & 0xf);
This sentence interpretation: (res << 1) + (res << 3), the left one is multiplied by 2, the left three are multiplied by 8, together equivalent res * 10;
(Str [i] & 0xf) is equivalent to str [i] - '0', why? Because of the low four bits of the character code value SACII '0' - '9' is 0 ~ 9, numeral 15 is 0xF, 1111 bits, then this operation can be '0' into 0, ..., the '9' is converted to '9'.
Overall this sentence: res = res * 10 + str [i] - '0'. For example, string is '123';
Then the single step: res = 1; res = 1 * 10 + 2 = 12; res = 12 * 10 + 3 = 12. This sentence is what it means.

 

 

Guess you like

Origin www.cnblogs.com/manmanchanglu/p/12577746.html