Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse decimal digits in javascript

Tags:

javascript

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

input:

x = 123; 

output:

x = 321; 

How Do this?

like image 521
The Mask Avatar asked Jun 15 '11 00:06

The Mask


2 Answers

Here is another way...

var reversed = num.toString().split('').reverse().join('');

jsFiddle.

If you wanted it again as a Number, use parseInt(reversed, 10). Keep in mind though, leading 0s are not significant in a decimal number, and you will lose them if you convert to Number.

like image 112
alex Avatar answered Sep 23 '22 02:09

alex


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;
}
like image 30
Ry- Avatar answered Sep 20 '22 02:09

Ry-