Share my java solution, though I don't get the point of this question.


  • 0
    M
    public int atoi(String str) {
        if(str.length()==0){
            return 0;
        }
        int sum=0;
        int i=0;
        while(str.charAt(i)==' ' && i<str.length()-1){
            i++;
        }
        if(i==str.length()){
            return 0;
        }
        if((str.charAt(i)<'0'||str.charAt(i)>'9')&&(str.charAt(i)!='-')&&(str.charAt(i)!='+')){
        	return 0;
        }
        StringBuffer sb=new StringBuffer();
        boolean plus=true;
        boolean sign=false;
        boolean start=true;
        while(i<=str.length()){
        	if(i==str.length()){
            	int num=toInt(sb.toString());
            	if(num==-1){
            		return plus?Integer.MAX_VALUE:Integer.MIN_VALUE;
            	}
                sum=plus?sum+num:sum-num;
                break;
            }
        	char c=str.charAt(i);
            if(c<='9'&& c>='0'){
            	if(start){
            		start=false;
            	}
                sb.append(c);
            }
            else if(c=='+'||c=='-'){
                if(sign){
                    return 0;
                }
                sign=true;
            	if(start){
            		start=false;
            		plus=c=='+'?true:false;
            	}
            	else{
            		int num=toInt(sb.toString());
                	if(num==-1){
                		return plus?Integer.MAX_VALUE:Integer.MIN_VALUE;
                	}
                    sum=plus?sum+num:sum-num;
                    plus=c=='+'?true:false;
                    sb=new StringBuffer();
            	}
            }
            else{
                if(sb.length()>0){
                    int num=toInt(sb.toString());
            	    if(num==-1){
            	    	return plus?Integer.MAX_VALUE:Integer.MIN_VALUE;
            	    }
                    sum=plus?sum+num:sum-num;
                    plus=c=='+'?true:false;
                    sb=new StringBuffer();
                    return sum;
                }
                else{
                    return sum;
                }
                
            }
    
            i++;
        }
        return sum;
    }
    public int toInt(String s){
    	if(s.length()>10){
    		return -1;
    	}
    	int sum=0;
    	for(int i=0;i<s.length();i++){
    		int pow=s.length()-i-1;
    		sum+=(int)Math.pow(10, pow)*(s.charAt(i)-'0');
    		if(sum<0){
    			return -1;
    		}
    	}
    	return sum;
    }

  • 0
    T

    is checking overflow based on (sum < 0) correct? It is highly possible that when it overflows, the sign bit got changed to 1, but it could also remain 0, depending on the real value of sum, right?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.