Reversing a Number using bitwise shift

荒凉一梦 提交于 2019-12-10 09:53:16

问题


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


回答1:


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.




回答2:


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;
}


来源:https://stackoverflow.com/questions/7472824/reversing-a-number-using-bitwise-shift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!