The mapping between 2s compl codes and their number strings
 

There is a mapping between the input 2s complement code to its corresponding number string:

 2's complement representation (32 bits) String representation
 ----------------------------------      ----------------------
 00000000000000000000000000000000               "0"           
 00000000000000000000000000000001               "1"          
 00000000000000000000000000000010	        "2"         
 00000000000000000000000000000011               "3"        
   ...                                          ...
 11111111111111111111111111111111              "-1" 
 11111111111111111111111111111110              "-2" 
 11111111111111111111111111111101              "-3" 
   ...                                          ...
   

The toString( ) method implements this mapping !!!

Naive way to implement the toString( ) mapping

  public static String toString( int x )
  {
     if ( x == 0 )      // Compares x with 00000000000000000000000000000000
        return "0"; // Returns the ASCII codes for string "0" !
     else if ( x == 1 ) // Compares x with 00000000000000000000000000000001
        return "1"; // Returns the ASCII codes for string "1" !
     else if ( x == 2 ) // Compares x with 00000000000000000000000000000010
        return "2";
     ...
     else if ( x == 10 )// Compares x with 00000000000000000000000000001010
        return "10"; // Returns the ASCII codes for string "10" !
     else if ( x == 11 )// Compares x with 00000000000000000000000000001011
        return "11";
     ...
     else if ( x == -1 )// Compares x with 11111111111111111111111111111111
        return "-1";
     else if ( x == -2 )// Compares x with 11111111111111111111111111111110 
        return "-2";
     ...
  }
   

Remember that the compiler will translate the characters into a ASCII code 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 integers !!!

    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ..., 100, 101, ..., 1000, 1001, ... and so on !

 

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

Before we proceed....
 

I must remind you that we write expressions in decimal:

   x = x % 10;
   x = x / 10;  
 

the computer program will perform the operations in binary:

   x = x (in bin) % 00000000000000000000000000001010;
   x = x (in bin) / 00000000000000000000000000001010;  

because the compiler will translate the expression into 2s complement code !!!