My Java solution using regular expression


  • 1
    W

    public class Solution {

        static int max = Integer.MAX_VALUE;
        static int min = Integer.MIN_VALUE;
        public int myAtoi(String str) {
                if(str == null || str.equals(""))
    		return 0;
    	
    	String regex = "^(\\s+)?(-|\\+)?\\d+(.*)?$";
    	if(!str.matches(regex)){
    		return 0;
    	}
    	
    	String temp = str.trim();
    	int sign = 1;
    	long sum=0;
    	for(int i=0; i<temp.length(); i++){
    		if(temp.charAt(i) == '-'){
    			sign = -1;
    		}else if(temp.charAt(i) == '+'){
    			sign = 1;
    		}else{
    			if(temp.substring(i, i + 1).matches("\\D"))  break;
    			sum = sum * 10 + Integer.parseInt(temp.substring(i, i + 1));
    		}
    		
    		if(sign == 1 && sum > max)
    			return max;
    		if(sign == -1 && sign * sum < min)
    			return min;
    	}
    	
    	return (int)sum * sign;
    }
    

    }


Log in to reply
 

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