0

I am trying to reverse an int,following is my code

int num = 1534236469,temp=num;

while (temp != 0) {
    digit = temp % 10;
    temp = temp / 10;
    sum = ((sum * 10) + digit);
}

At the 2nd final iteration i get 964632435,which is as expected,but at the last iteration out of nowhere i get 1056389759..

Can someone help me understand what is happening here?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373

1 Answers1

0

It is definitely int overflow.

int num = 1534236469,temp=num;
int sum = 0;
while (temp != 0) {
    int digit = temp % 10;
    temp = temp / 10;
    sum = ((sum * 10) + digit);
    System.out.printf("%,14d  %,14d%n",sum, Integer.MAX_VALUE);
}

prints

             9   2,147,483,647
            96   2,147,483,647
           964   2,147,483,647
         9,646   2,147,483,647
        96,463   2,147,483,647
       964,632   2,147,483,647
     9,646,324   2,147,483,647
    96,463,243   2,147,483,647
   964,632,435   2,147,483,647
 1,056,389,759   2,147,483,647

Compare the left to the int maximum on the right. What happens when you compute the last value and multiply 964,632,435 by 10?

Extract from the Java Language Specification - multiplication operator

"If an integer multiplication overflows, then the result is the low-order bits of the mathematical product as represented in some sufficiently large two's-complement format. As a result, if overflow occurs, then the sign of the result may not be the same as the sign of the mathematical product of the two operand values"

Here is an example.

long v = 964_632_435;
v *= 10;
System.out.println("long value * 10 = " + v);
v = v&Integer.MAX_VALUE; // mask off high order 33 bits in the long
                         // remember that largest int value is 31 bit value
                         // of all ones or x7FFF_FFFF
System.out.println("long after mask = " + v);
System.out.println("long adding 1   = " + (v+1));

prints

long value * 10 = 9646324350
long after mask = 1056389758
long adding 1   = 1056389759

And one final example using bit strings.

String bits = Long.toBinaryString(9646324350L);
System.out.println("long value = "  + bits);
int len = bits.length();

bits = bits.substring(len-31, len);
System.out.println("low order 31 bits = " + bits);
int val = Integer.parseInt(bits,2);
System.out.println("Overflow value = " + val);

prints

long value = 1000111110111101110011101001111110
low order 31 bits = 0111110111101110011101001111110
Overflow value = 1056389758  (before adding 1)

WJS
  • 36,363
  • 4
  • 24
  • 39
  • Compare the left to the int maximum on the right. What happens when you compute the last value and multiply 964,632,435 by 10? --- that is the part i am curious about.. – Santhosh N S Jun 26 '22 at 16:03
  • @SanthoshNS Please see my updated answer. – WJS Jun 27 '22 at 22:40