0
    int x = -2147483648;
    boolean negative = false;
    if(x<0){
        negative=true;
        x=(0-x);
    }
    long k = x;
    long reverseNum = 0;
    while(k!=0){
        reverseNum *= 10;
        reverseNum += k % 10;
        k /= 10;
    }
    if( reverseNum>Integer.MAX_VALUE)
        System.out.println(0);
    else
        System.out.println(negative ? 0-(int)reverseNum : (int)reverseNum);

It should return 0 but it is returning -126087180

It is working fine when I move "long k = x" to second line of code.

Can someone help me in understanding what is the actual issue with the code implementation and why I am getting a different result in the first case?

jps
  • 20,041
  • 15
  • 75
  • 79
  • The range of `int` is from -2147483648 to 2147483647. 0-x, which would be `+2147483648` does not fit into an `int`. It does fit into a `long`. –  Aug 01 '21 at 21:15
  • yea , it was a silly mistake from my end . I just did not saw the range . thank you – Roshan Choudhary Aug 02 '21 at 09:51

1 Answers1

0

The problem is pretty simple. In your case int ranges from -2,147,483,648(MIN_VALUE) to 2,147,483,647(MAX_VALUE).

Thus, at the second line in the if statement where x=(0-x) occur, you can refer to it as MAX_VAULE +1 which makes it overflow. Therefor x will contain the same negative number.

What Is Integer Overflow