My ugly java code


  • 0
    public class Solution {
        public int myAtoi(String str) {
            str=str.trim();
            if(str.isEmpty())
                return 0;
            int len=str.length();
            long ans=0;
            boolean flag1=false;
            boolean flag2=false;
            for(int i=0;i<len;++i){
                if(str.charAt(i)>='0'&&str.charAt(i)<='9'){
                    ans*=10;
                    ans+=str.charAt(i)-'0';
                    if(ans>Integer.MAX_VALUE)
                        break;
                }
                else if(str.charAt(i)=='-'){
                    if(flag2||flag1)
                        return 0;
                    flag1=true;
                }
                else if(str.charAt(i)=='+'){
                    if(flag2||flag1)
                        return 0;
                    flag2=true;
                }
                else
                    break;
            }
            if(flag1&&flag2)
                return 0;
            if(!flag1&&ans>Integer.MAX_VALUE)
                return Integer.MAX_VALUE;
            if(flag1&&ans>Integer.MAX_VALUE)
                return Integer.MIN_VALUE;
            return flag1?(int)-ans:(int)ans;
        }
    }

Log in to reply
 

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