String——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.

Analysis

The following cases should be considered for this problem:

1. null or empty string
2. white spaces
3. +/- sign
4. calculate real value
5. handle min & max
 public int atoi(String str) {
        if(str == null||str.length() == 0)//1.判断是否为空串
            {
            return 0;
        }
        str=str.trim();//2.去除字符串前的空格
        char flag='+';
        
        long result=0;//这里若设为int型,当字符串数值超出int型时会变为负数;
        int index=0;
        if(str.charAt(0) == '+')//判断字符串首是否有正负号;
            {
            index++;
        }
        else if(str.charAt(0) == '-')
            {
            flag='-';
            index++;
        }
        //输出第一个非法字符前的数字;
        while(index<str.length()&&str.charAt(index)>='0'&&str.charAt(index)<='9')
            {
            result=result*10+str.charAt(index)-'0';
            index++;
        }
        
        if(flag == '-')
            {
            result=-result;
        }
        if(result>Integer.MAX_VALUE)//Integer方法中的int型常量的MAX2^31-1和MIN-2^31-1;
            {                        //java中没有无符号数,首尾都为符号位;
            return Integer.MAX_VALUE;
        }
        else if(result<Integer.MIN_VALUE)
            {
            return Integer.MIN_VALUE;
        }
        else
            {
            return (int)result;//将long型转换为int型;
        }
    }









啊实打实的

你可能感兴趣的:(String——string-to-integer-atoi)