What's wrong with my java code?


  • 0
    X
    public class Solution {
    public int myAtoi(String str) {
        if((str!=null)&&(str!="")){
    		str=str.trim();
    		if(str.charAt(0)=='+'||str.charAt(0)=='-'){
    			int length=findthefirstnotdigit(str,1);
    			if(length==0)
    				return 0;
    			else{
    				str=str.substring(0, length+1);
    				long l=Long.parseLong(str);//这个方法可以处理第一位是+或者-的情况
    				if(l>Integer.MAX_VALUE)
    					return Integer.MAX_VALUE;
    				else if(l<Integer.MIN_VALUE)
    					return Integer.MIN_VALUE;
    				else
    					return (int)l;
    			}
    		}
    		else if(str.charAt(0)>='0'&&str.charAt(0)<='9'){
    			int length=findthefirstnotdigit(str,1);
    			str=str.substring(0, length+1);
    			long l=Long.parseLong(str);//这个方法可以处理第一位是+或者-的情况
    			if(l>Integer.MAX_VALUE)
    				return Integer.MAX_VALUE;
    			else if(l<Integer.MIN_VALUE)
    				return Integer.MIN_VALUE;
    			else
    				return (int)l;
    		}
    		else
    			return 0;
    	}
    	else
    	return 0;
    }
    public static int findthefirstnotdigit(String str,int begin){
    	int index=0;
    	for(int i=begin;i<str.length();i++){
    		if(Character.isDigit(str.charAt(i))){
    			index=i;
    		}
    		else
    			break;
    	}
    	return index;
    }
    

    }

    it said that Runtime Error Message:Line 5: java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    Last executed input: ""


Log in to reply
 

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