部分文章内容为公开资料查询整理,原文出处可能未标注,如有侵权,请联系我,谢谢。邮箱地址:gnivor@163.com ►►►需要气球么?请点击我吧!

LeetCode--8. String to Integer (atoi)

大意:将字符串转换成数字

需要注意:
数字前有空格
数字中间有非数字字符(字母后面的舍弃)
存在多个正负号(返回0)

public static int myAtoi(String str) {
    str = str.trim(); //去掉前面的空格
    long solu =0;
    long maxint = Integer.MAX_VALUE;
    int len = str.length();
    boolean isPositive = true;
    boolean flag = false;
    char c ; 
    for(int i = 0 ; i <len ;i++){
        c = str.charAt(i);
        if(c == '-'||c=='+'){
            if(flag == true)
                return 0;
            else{
                if(c=='-')
                    isPositive = false;
                flag = true;
            }
        }
        
        else if(c >'9'||c<'0')
            break;
        else {
            solu = solu*10+c-'0';
            if(solu>maxint&&isPositive==true)
                return Integer.MAX_VALUE;
            if(solu>maxint+1&&isPositive == false){
                return Integer.MIN_VALUE;
            }
        }
                        
    }
    if( isPositive == false)
        solu = - solu;
    
    return (int)solu;
}

测试用例:

public static void main(String args[]){
    System.out.println(myAtoi("-111"));
    System.out.println(myAtoi("0000"));
    System.out.println(myAtoi("         15"));
    System.out.println(myAtoi("         1asdf67"));
    System.out.println(myAtoi("         2147483648"));
    System.out.println(myAtoi("         -2147483648"));
    System.out.println(myAtoi("         -2147483649"));
    System.out.println(myAtoi("+-5"));
    System.out.println(myAtoi("         010"));
}

 

posted @ 2015-07-14 15:46  流了个火  阅读(98)  评论(0)    收藏  举报
►►►需要气球么?请点击我吧!►►►
View My Stats