The mapping between number strings and their 2s compl codes
 

There is a mapping between the input (number) strings to their corresponding 2s complement code:

    Input string   2's complement representation (32 bits)
   -------------   --------------------------------
      "0"   <-->   00000000000000000000000000000000
      "1"   <-->   00000000000000000000000000000001
      "2"   <-->   00000000000000000000000000000010
      "3"   <-->   00000000000000000000000000000011
      ...          ...
      "15"  <-->   00000000000000000000000000001111

      "-1"  <-->   11111111111111111111111111111111
      "-2"  <-->   11111111111111111111111111111110
      "-3"  <-->   11111111111111111111111111111101
      ...          ...
   

The parseInt( ) implements this mapping !!!

Naive way to implement the parseInt( ) mapping

  public static int parseInt( String s )            
  {
     if ( s.equals("0") )
        return 0;  // returns: 00000000000000000000000000000000 
     else if ( s.equals("1") )
        return 1;  // returns: 00000000000000000000000000000001
     else if ( s.equals("2") )
        return 2;  // returns: 00000000000000000000000000000010
     ...
     else if ( s.equals("10") )
        return 10; // returns: 00000000000000000000000000001010
     else if ( s.equals("11") )
        return 11; // returns: 00000000000000000000000000001011
     ...
     else if ( s.equals("-1") )
        return -1; // returns: 11111111111111111111111111111111
     else if ( s.equals("-2") )
        1eturn -2; // returns: 11111111111111111111111111111110    
     ...
  }
   

Remember that the compiler will translate every number into a 2s compl (binary) representation !!!

The problem with this naive solution...
 

  • It's impossible to write !!!

    You will need to write out every possible input string

    There are 232 (over 4 trillion !) input strings !!!

 

Now that we know what parseInt( ) must do, let's develop the algorithm in a piece meal fashion