【LeedCode】String to integer(atoi)

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.

列举需要注意的集中情况

1、去空格 trim()

2、首字母为“+”或者“-”,则要记录下来。设一个flag变量,用于存储符号位

3、数字前出现了非数字字符,则返回0

4、在数字中出现了非数字字符,则返回前面的一些数字字符组成的数,后面的直接舍弃

5、存在数字越界的情况,所以要对最后得到的数字进行判断

public static int atoi(String str){
        if(str == null || str.length() == 0)
        {
            return 0;
        }
        str = str.trim();
        int flag = 1;
        int start = 0;
        long res = 0;
        if(str.charAt(0)=='+'){
            flag = 1;
            start++;
        }else if(str.charAt(0)=='-'){
            flag = -1;
            start++;
        }
        for(int i = start;i<str.length();i++){
            if(Character.isDigit(str.charAt(i))){
                return (int)res*flag;
            }
            res = res*10 + str.charAt(i)-'0';        
        }
        if (flag == 1 && res > Integer.MAX_VALUE)
            return Integer.MAX_VALUE;
        if (flag == -1 && (-1) * res < Integer.MIN_VALUE)
            return Integer.MIN_VALUE;
        
        return (int)(flag * res);
        
    }

 

posted @ 2017-03-16 22:28  小猴子爱吃桃  阅读(200)  评论(0编辑  收藏  举报