Reverse decimal digits in javascript

后端 未结 14 921
灰色年华
灰色年华 2021-02-05 16:24

How do I reverse the digits of a number using bitwise?

input:

x = 123; 

output:

x = 321; 
14条回答
  •  闹比i
    闹比i (楼主)
    2021-02-05 17:09

    That's not inverting bits; that's reversing the order of decimal digits, which is completely different. Here's one way:

    var x = 123;
    var y = 0;
    for(; x; x = Math.floor(x / 10)) {
        y *= 10;
        y += x % 10;
    }
    x = y;
    

    If you actually want to invert bits, it's:

    x = ~x;
    

    As a function:

    function reverse(n) {
        for(var r = 0; n; n = Math.floor(n / 10)) {
            r *= 10;
            r += n % 10;
        }
        return r;
    }
    

提交回复
热议问题