开发者

Reversing a Number using bitwise shift

开发者 https://www.devze.com 2023-04-05 17:22 出处:网络
I am trying to find a way to reverse a number without Converting it to a string to find the length Reversing the string and parsing it back

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 currentl开发者_如何学Cy 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


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.


How about this? It handles negative numbers as well.

public int getReverse(int num){
   int rst=0;
   int sign;
   sign=num>0?1:-1;

   num*=sign;
   while(num>0){
      int lastNum = num%10;
      rst=rst*10+lastNum
      num=num/10;
   }
   return rst*sign;
}


Integer.MAX_VALUE or Integer.MIN_VALUE is not at all considered in any of the solutions.

For eg: if the input is -2147483647 or 2147483647 the o/p will be 1126087180 and -1126087180 respectively.

Please try the below solutions where both the conditions are handled, so if at any point of time the number is going beyond the boundary conditions i.e., INPUT_VALUE > Integer.MAX_VALUE or INPUT_VALUE < Integer.MIN_VALUE it would return 0

class ReversingIntegerNumber {
    
    public int reverse(int originalNum) {
        boolean originalIsNegative = originalNum > 0 ? false : true;
        int reverseNum = 0;
        int modValue;
        originalNum = Math.abs(originalNum);
        while(originalNum != 0) {
            modValue = originalNum % 10;
            if(reverseNum > (Integer.MAX_VALUE - modValue)/10) {
                return 0;
            }
            reverseNum = (reverseNum * 10) + modValue;
            originalNum /= 10;
        }
        return originalIsNegative ? -1 * reverseNum : reverseNum;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号