Reversing a Number using bitwise shift

China☆狼群 提交于 2019-12-05 19:17:49

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.

Ivan

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