leecode---08---Basic data type conversion---str to integer

 
 
meaning of the title
convert a string to an integer
 
 
analyze
The main problem is the judgment of boundary conditions.
1. Remove the spaces first, str = str.trim();
2. The first character may or may not be a symbol. Special judgment is made on the first character.
3. Use a temporary double to store the number and traverse each character of str from left to right.
4. Finally, determine the symbol
5. Out of bounds judgment
 
code
class Solution {
    public int myAtoi(String str) {
        if (str == null || str.length() == 0) return 0;
        
        double result = 0;//Used to save the final result
        char flag = '+';//Used to save the sign
        int index = 0;//Use index to point to the subscript to move
        
        str = str.trim();//Remove spaces and the first sign
        if (str.charAt(0) == '-') {
            flag = '-';
            index++;
        } else if (str.charAt(0) == '+') {
            index++;
        }
        
        //Then start to judge from the second number, if there is a non-character directly interrupt
        for (; index < str.length(); index++) {
            char c = str.charAt(index);
            if (c >= '0' || c <= '9') {//Normal numbers are inserted from front to back
                result = result * 10 + (c - '0');
                index++;
            } else {
                return 0;
            }
        }
        
        //Finally, because the result exists in the result, it is necessary to judge the positive and negative signs and judge the out-of-bounds
        if (flag = '-') result = -result;
        if (result > INTEGER.MAX_VALUE) return INTEGER.MAX_VALUE;
        if (result < INTEGER.MIN_VALUE) return INTEGER.MIN_VALUE;
        return result;
    }
}
 
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326308039&siteId=291194637