My examplained long JAVA solution


  • 0
    J

    This problem was purposely made to be ambiguous. It was a pain and required a lot of work.

    public class Solution {
        public int myAtoi(String str) {
            
            String tempStr = "";
            char current;
            boolean negative = false;
            int answer = 0;
            boolean expressionThreshold = false;
            
            // return if str is length 0
            if(str.length() == 0)
                return 0;
            
            // eliminate whitespaces
            str = str.trim();
            
            // return if str length is 0 after trimming (it only had whitespaces)
            if(str.length() == 0) return 0;
            
            
            // process arithmetic operators
            OUTER:
            for(int i = 0; i < str.length(); i++){
                current = str.charAt(i);
                
                switch(current){
                    case '+':
                        if(expressionThreshold) break OUTER;
                        negative = false;
                        expressionThreshold = true;
                        break;
                    case '-':
                        if(expressionThreshold) break OUTER;
                        negative = true;
                        expressionThreshold = true;
                        break;
                    case ' ':
                        break OUTER;
                    default:
                        if(Character.isDigit(current)){
                            tempStr += str.charAt(i);
                            expressionThreshold = false;
                        } else{
                            break OUTER;
                        }
                }
                
            }
            
            // if only arithmetic operators were found
            if(tempStr.equals("")) return 0;
            
            // check if the number is larger than 32-bit signed integer (cannot parse)
            try{
                
                answer = Integer.parseInt(tempStr);
                
            } catch(NumberFormatException e){
                
                if(negative){
                    
                    return Integer.MIN_VALUE;
                    
                } else{
                    
                    return Integer.MAX_VALUE;
                }
                
            }
            
            // if it was negative to begin with, make it negative again
            if(negative){
                
                answer *= -1;
                
            }
            
            return answer;
        }
        
    }
    

Log in to reply
 

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