Easy Java Solution (Use regex)


  • 0
    W

    class Solution {
    public int myAtoi(String str) {
    str=str.trim();
    if(str==""||str.isEmpty())
    return 0;
    try{
    String [] splits=str.split("\D");
    if(splits.length>=2&&splits[0].isEmpty()){
    if(splits[1].isEmpty())
    return 0;
    splits[0]=splits[1];
    }
    if(str.startsWith("-"+splits[0])){
    return Integer.parseInt("-"+splits[0]);
    }
    else if(str.startsWith("+"+splits[0])){
    return Integer.parseInt(splits[0]);
    }
    else if(str.startsWith(splits[0])){
    return Integer.parseInt(splits[0]);
    }
    else{
    throw new Exception();
    }

        }
        catch (NumberFormatException e){
            if(str.startsWith("-")){
                return Integer.MIN_VALUE;
            }
            else{
                return Integer.MAX_VALUE;
            }
        }
        catch(Exception e){
            return 0;
        }
    }
    

    }


Log in to reply
 

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