An algorithm:
Please come to implement a atoi
function, it can convert a string to an integer.
First, the function will begin with a space character discard useless if necessary, until the find to the first non-space character so far.
When we find the first non-space character is a positive or negative number, the combination of the symbols as much as possible with consecutive numbers up later, as the sign of integer; if the first non-space character is figures, which directly after the continuous numeric characters are combined to form an integer.
In addition to the string after a valid integer part may also exist extra characters, these characters can be ignored, they should not affect a function.
Note: if the character string in the first non-space character is not a valid integer character string is empty or contains only white space character string, then you will not need to be a function of conversion.
In any case, if the function can not effectively convert, 0 is returned.
Description:
We assume that the environment can store 32-bit signed integer size, then the numerical range [-231 231--1]. If the value exceeds this range, return INT_MAX (231 - 1) or INT_MIN (-231).
Example 1:
Input: "42" Output: 42
Example 2:
Input: "-42" Output: -42 Explanation: a first non-blank character '-', it is a negative sign. We will all digital consecutive negative number and later combined as much as possible, and finally get -42.
{Solution class public int myAtoi (String STR) { int m = 0; // only the first digit encountered before or sign BREAK for (; m <str.length (); m ++) { char = CH STR. the charAt (m); IF (CH == '+' || CH == '-') { BREAK; } the else IF (CH> = '0' && CH <= '. 9') { BREAK; } the else IF ( ! CH = '') { return 0; } } // will bounds determined whether m iF (m> = str.length ()) { return 0; } int RES = 0; // K is used to indicate a positive sign -1 negative int k = 1; IF (str.charAt (m) == '-') { K = -1; m ++; } the else IF (str.charAt (m) == '+') { m ++; } the while (m <str.length ( )) { char CH = str.charAt (m ++); IF (CH> = '0' && CH <= '. 9') { // the character to an integer int A = CH - '0'; // n Analyzing whether the number of overflow iF (K ==. 1 && (RES> Integer.MAX_VALUE / 10 || (RES Integer.MAX_VALUE == / 10 && A>. 7))) { return Integer.MAX_VALUE; } iF (K == - 1 && (res * k <Integer .MIN_VALUE/ 10 || (res * k == Integer.MIN_VALUE /10 && a > 8 ))){ of Integer.MIN_VALUE return; } RES = RES + A * 10; } the else { BREAK; } } // returns the result, multiplied by k (k representatives are positive or negative) return RES * k; } }
2 English documentation: https://github.com/LMAX-Exchange/disruptor/wiki/Introduction This is the disruptor ah tell Java cache by using a computer program, improve project performance