Leetcode 8. String to Integer

class Solution {
    public int myAtoi(String str) {
        long res=0;
        int flag=-1;
        int start=-1;
        for(int i=0;i<str.length();i++){
            if(flag==-1 && str.charAt(i)==' '){
                continue;
            }
            else if(flag==-1 && str.charAt(i)=='+'){
                flag=0;
                continue;
            }
            else if(flag==-1 && str.charAt(i)=='-'){
                flag=1;
                continue;
            }
            else if(str.charAt(i)<='9'&& str.charAt(i)>='0'){
                start=i;
                break;
            }
            else{
                return 0;
            }
        }
        if(start!=-1){
            for(int j=start;j<str.length();j++){
                if(str.charAt(j)<='9'&& str.charAt(j)>='0'){
                    if(res>=Integer.MAX_VALUE){
                        break;//if this line not exists, “9223372036854775808” will output -2147483648. 9223372036854775800+8 will become -9223372036854775808
                    }
                    res=res*10+str.charAt(j)-'0';
                }
                else{
                    break;
                }
            }
        }
        if(flag==1 && res!=0){
            res=-res;
        }
        
        if(res>=Integer.MAX_VALUE){
            return Integer.MAX_VALUE;
        }
        if(res<=Integer.MIN_VALUE){
            return Integer.MIN_VALUE;
        }
        return (int)res;
    }
}
···

猜你喜欢

转载自blog.csdn.net/u014731993/article/details/84009330