Simple Algorithm for Black box testing atoi


  • 0
    G

    This problem is an exercise in black box testing, where the vague output and vague input must be accounted for. So through testing, it's expecting you to find the correct outputs for the vast amount of different inputs. Through testing, it's simple to find that the expected output is the first stand-alone number in the string. However, there are a few niches in testing.

    i.e. What do you do with stand-alone '+' or '-'? The expected return is 0 because "+\s" or "-\s" is considered shorthand for +0 or -0, both of which are equal to 0.

    The algorithm presented is the more simple way to success all test cases.

    1. Trim the input, most test cases include leading and/or trailing whitespace. As the following steps might split on whitespace, it's simpler to remove leading or trailing whitespace.

    2. If there remains whitespace, symbols, or text, split on all.

    3. atod on either the first element on the split or the trimmed input

    4. if atod returns an error return 0 else return the int value of the double

    Edge Case : input is Integer.MAX_VALUE + 1, return Integer.MAX_VALUE. This is why the algorithm uses atod instead of atoi, atoi will return an Exception while atod will return a double which we can convert.

    import java.util.regex.*;
    
    class Solution {
        private static final String splitOn = "[^\d+-]";
        
        public int myAtoi( String str ) {
            String s = str.trim();
            if( s.length() == 0 || s.startsWith("[+-]\\s") )
                return 0;
            Matcher m = Pattern.compile( splitOn ).matcher( s );
            if( m.find() ) {
                String[] segments = s.split( splitOn );
                return segments.length == 0 ? 
                            0 : 
                            parseInt(  segments[0]  );
            }else{
                return parseInt( s );
            }
        }
        
        private static int parseInt( String str ){
            if( str.trim().length() == 0 )
                return 0;
            try{
                return ( ( Number )Double.parseDouble( str.trim() ) ).intValue() ;
            }catch( java.lang.NumberFormatException e ){
                return 0;
            }
        }
    }
    

Log in to reply
 

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