Home > Back-end >  Palindrome says infinity when compared in the final if statement
Palindrome says infinity when compared in the final if statement

Time:11-18

ok so I have been going at it for a while im making a palindrome program on html for the first time but when I input 111 it says its not a palindrome even tho i went through the while loop with a calc and it should be the same. I checked the outputs by revealing em and "input" = 111. "temp" = 0 as it should. "reversed" tho is equal to infinity lol and idk y any help is appreciated.

function Palindrome() {
    let input = document.querySelector("#userInput").value;
    var temp = input;
    let reversed = 0;

    while (temp > 0) {
        const lastDigit = temp % 10;
        reversed = (reversed * 10)   lastDigit;
        temp = (temp / 10);
    }
    if (input == reversed) {
        document.querySelector("#answer").innerHTML = `This is a Palindrome `;
    }else {
        document.querySelector("#answer").innerHTML = `This is not a Palindrome ${input} ${temp} ${reversed} `;
    }
}

CodePudding user response:

You're doing floating point division, so temp will never be more than 0 until you do many iterations and get floating point underflow. After each iteration it becomes 11.1, then 1.11, then 0.111, .0111, and so on. This is multiplying reversed by 10 each time, and it eventually overflows to infinity.

Round the number when dividing so that the fraction will be discarded:

temp = Math.round(temp / 10);

function Palindrome(input) {
  var temp = input;
  let reversed = 0;

  while (temp > 0) {
    const lastDigit = temp % 10;
    reversed = (reversed * 10)   lastDigit;
    temp = Math.round(temp / 10);
  }
  if (input == reversed) {
    console.log(`This is a Palindrome ${input}`);
  } else {
    console.log(`This is not a Palindrome ${input} ${temp} ${reversed} `);
  }
}

Palindrome(111);
Palindrome(123)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

As Barmar explained in his answer about percent division try to git rid of it!

function Palindrome() {
  let input = document.querySelector("#userInput").value;
  //convert input to number
  var temp =  input;//or parseInt(input)
  let reversed = 0;
  while (temp > 0) {
    const lastDigit = temp % 10;
    reversed = reversed * 10   lastDigit;
    temp = Math.floor(temp / 10);//<-- to prevent Infinity
  }
  if (input == reversed) {
    document.querySelector("#answer").innerHTML = `This is a Palindrome `;
  } else {
    document.querySelector(
      "#answer"
    ).innerHTML = `This is not a Palindrome ${input} ${temp} ${reversed} `;
  }
}
<input type="input" value="" id="userInput">
<input type="button" value="Is Palindrom" onclick="Palindrome()">
<div id='answer'></div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related