Reverse decimal digits in javascript

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;
}

If you wanted to make a simple reversal:

var x = 123;
var y = x.toString();
var z = y.split("").reverse().join("");
var aa = Number(z);
document.write(aa);

http://jsfiddle.net/jasongennaro/gV39e/

Tags:

Javascript