Quang Nguyen Quang Nguyen - 1 month ago 17
Javascript Question

Reverse and Add in JavaScript

I've been working on an algorithm in javascript that solves a "reverse and add" proble. I've worked it out in my head and it should work, but whenever I try to run it in JSFiddle it just becomes unresponsive. I think it may be in an infinite loop, but i'm not sure why. Here is the code:

HTML

<p id="test"></p>


JAVASCRIPT

var x = 124;
function reverse(n) {
for(var r = 0; n; n = Math.floor(n / 10)) {
r *= 10;
r += n % 10;
}
return r;
}
while(x != reverse(x)) {
x =+ reverse(x)
document.getElementById("test").innerHTML = x
}

Answer

The code below keeps reversing the variable

while(x != reverse(x)) {
        x =+ reverse(x)
}

If you run reverse(124) you get 421. If you run reverse(421) you get 124. Now, let's see what happens:

Starting with x = 124, we enter the loop:

  1. x != reverse(x) => 124 != reverse(124) => 124 != 421 => true

  2. x =+ reverse(x) => x =+ reverse(124) => x =+ 421 => x = 421

  3. x != reverse(x) => 421 != reverse(421) => 421 != 124 => true

  4. x =+ reverse(x) => x =+ reverse(421) => x =+ 124 => x = 124

And back to step 1.


When you say that you are trying to solve the "reverse and add" problem, I understand that you want to actually add.

That is, =+ is probably a typo, and what you want is +=. That will take 124 reverse it to 421 add it to get 545 and then it is no longer different than its reverse. Similar to what Thalaivar explains.

Instead code of the form x =+ value is doing a unary + on value and then it assigns that to x.