Reversing a Number using bitwise shift

后端 未结 2 1074
不知归路
不知归路 2021-01-14 13:42

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
相关标签:
2条回答
  • 2021-01-14 14:25

    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.

    0 讨论(0)
  • 2021-01-14 14:25

    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;
    }
    
    0 讨论(0)
提交回复
热议问题