Beats 99.3% Java Submissions


  • 0
    S
    public class Solution {
        public int myAtoi(String s) {
            int len = s.length();
            int i=0,flg=0,fin1=0;
            long fin=0;
            //System.out.println(Integer.MAX_VALUE);
            //System.out.println(Integer.MIN_VALUE);
            
            // removing the space
            while(i<len && s.charAt(i)==' ' ) i++;
            
            // sign
            if(i<len && s.charAt(i)=='+') 
            {
                flg=0;
                i++;
            }
            else if(i<len && s.charAt(i)=='-'){
                flg=1;
                i++;
            }
             
            //if(fin>=Integer.MAX_VALUE) return Integer.MAX_VALUE;
            //else if(fin<=Integer.MIN_VALUE && flg==1) return Integer.MIN_VALUE*-1;
            
            while(i<len){
                int tmp = s.charAt(i)-'0';
                if(tmp>=0 && tmp<10) fin=fin*10+tmp;
                else break;
                
                if(fin>Integer.MAX_VALUE && flg==0) return Integer.MAX_VALUE;
                else if(fin*-1<=Integer.MIN_VALUE && flg==1) return Integer.MIN_VALUE;
                //System.out.println("fin : " + fin);
                i++;
            }
            fin1=Math.toIntExact(fin);
            return flg==1?fin1*-1:fin1;
        }
    }
    

Log in to reply
 

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