Q:

In reversing an integer , I am using two duplicated while loops, is there any way to refactor those while loops and instead use one?

public int reverse(int x) { 
    byte TEN=10; 
    long rev=0;
    if(x<0) {
        while(x<0) {
            rev = TEN*rev+(x%10);
            x /= 10;
        }      
    } else {
        while(x>0) {
            rev = TEN*rev+(x%10);
            x /= 10;
        }
    }      
    if(rev>2147483647 || rev<-2147483648) {
        return 0;
    } 
    return (int) rev;
}

I am unable to remove the duplicated while loop, is this the only way , else anyone help me to achieve this! Thanks in advance.

A:

For the original version of this question: since x is not modified in either of the original loops:
while (true) {
    I want mango;
    I want apple;
}

For the updated version:
public int reverse(int x) { 
    byte TEN = 10; 
    long rev = 0;
    if (x != 0) {
        int sign = x < 0 ? -1 : +1;
        do {
            rev = TEN * rev + (x % 10);
            x /= 10;
        } while (x * sign > 0);     
    }     
    if (rev > 2147483647 || rev < -2147483648) {
        return 0;
    } 
    return (int) rev;
}

(Challenge: there is a subtle reason why you need to turn the while into a do ... while.  See if you can figure it out.)
But in my mind there is no doubt that the original code is better.  For a start, it is a lot easier to understand, than this or similar rewrites.  (Duplication is NOT bad if it helps you understand what the code is doing.)

