Reversing a Number using bitwise shift

后端 未结 2 1077
不知归路
不知归路 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.

提交回复
热议问题