Share java solution


  • 0
    M
    public class Solution {
    public int myAtoi(String str) {
      if(str.trim().equals(""))
    		return 0;
    	long res = 0;
    	int sign = 1, i = 0;
    	str = str.trim();
               //sign
    	if (str.charAt(i) == '-' || str.charAt(i) == '+') {
    		sign = str.charAt(i) == '-'?-1:1;
    		i++;
    	}
    	
    	for(;i<str.length(); i++){
    		
    		if(str.charAt(i)>='0' && str.charAt(i)<='9'){
    			
                                    //  integer overflow
    			if(res*sign>=Integer.MAX_VALUE)
    				return Integer.MAX_VALUE;
    			if(res*sign<=Integer.MIN_VALUE)
    				return Integer.MIN_VALUE;
    			res = res*10+(str.charAt(i)-'0');
    			
    		}else{
    			if(res*sign>=Integer.MAX_VALUE)
    				return Integer.MAX_VALUE;
    			if(res*sign<=Integer.MIN_VALUE)
    				return Integer.MIN_VALUE;
    			return (int)res*sign;
    		}
    			
    	}
    	if(res*sign>=Integer.MAX_VALUE)
    		return Integer.MAX_VALUE;
    	if(res*sign<=Integer.MIN_VALUE)
    		return Integer.MIN_VALUE;
    	return (int)(res*sign);
    }
    

    }


Log in to reply
 

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