Search code examples
javanumbersbit-manipulationreverse

Reversing a Number using bitwise shift


I am trying to find a way to reverse a number without

  1. Converting it to a string to find the length
  2. Reversing the string and parsing it back
  3. Running a separate loop to compute the Length

i am currently doing it this way

 public static int getReverse(int num){
        int revnum =0;
        for( int i = Integer.toString(num).length() - 1 ; num>0 ; i-- ){
            revnum += num % 10 * Math.pow( 10 , i );
            num /= 10;
        }
        return revnum;        
    }

But I would Like to implement the above 3 conditions.

I am looking for a way , possibly using the bit wise shift operators or some other kind of bitwise operation.

Is it possible ? If so how ?

PS : If 1234 is given as input it should return 4321. I will only be reversing Integers and Longs


Solution

  • How about:

    int revnum = 0;
    while (num != 0) {
      revnum = revnum * 10 + (num % 10);
      num /= 10;
    }
    return revnum;
    

    The code expects a non-negative input.

    This may or may not matter to you, but it's worth noting that getReverse(getReverse(x)) does not necessarily equal x as it won't preserve trailing zeroes.