Why the expect output of "+-2" is "0" ?


  • 0
    C

    public class Solution {

    public int myAtoi(String str) {
        if(str == null || str.length() == 0)
            return 0;
        
        boolean isNegative = false;
        str = str.trim();
        
        if(str.charAt(0) == '-'){
            isNegative = true;
        }
        
        str = str.replaceAll("[^\\d.]", "");
        
        if(str.length() == 0)
            return 0;
            
        if(str.length() > 10){
            if(!isNegative)
                return Integer.MAX_VALUE;
            return Integer.MIN_VALUE;
        }
        
        long num = Long.valueOf(str).longValue();
        if(isNegative) num = -num;
        
        if((int)num > Integer.MAX_VALUE){
            return Integer.MAX_VALUE;
        }
        
        if((int)num < Integer.MIN_VALUE){
            return Integer.MIN_VALUE;
        }
       
        return (int)num;
    }
    

    }


  • 0
    E

    Because there is only 1 '-' or '+' here. when you meet '-', you should just return the result 0


  • 0
    T

    “ takes an optional initial plus or minus sign followed by as many numerical digits as possible”

    +-ismore than one,so it's invalide input, return 0.


  • 0
    This post is deleted!

  • 0
    Y

    why can't we just ignore the +, because - is a minus sign followed by as many as numerical digits as possible?


Log in to reply
 

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