0

This function is not sum correctly. sum=1 aj=121
sum=12 aj=12
sum=121 aj=1
This is not show in the alert.

// declaring the recursive function
///////////////////////////////////////////////////
function isPal(aj, n) {
  var sum = 0;
  //alert("aj=" + aj);
  if (Math.trunc(aj) != 0) {

    sum = sum * 10 + aj % 10;

    alert("sum=" + sum + " aj= " + aj + " n=" + n);
    isPal(aj / 10, n); // recursive call same as while(n!=0) using loop
  } else if (sum == n)
    return 1;
  else
    return 0;
}
////////////////////////////////////////////////////
var palindrome;
n = parseInt(prompt("Enter a number to check for Palindrome", "121"));
palindrome = isPal(n, n);
alert("palindrome = " + palindrome);
if (palindrome == 1)
  alert(n + " is palindrome\n");
else
  alert(n + " is not palindrome\n");
Not A Bot
  • 2,474
  • 2
  • 16
  • 33
challote
  • 35
  • 4
  • 2
    `sum = sum * 10 + aj % 10;` what good is this, if just before, you set `var sum = 0;`? Why not just `sum = aj % 10;`? This looks like a semantic mistake. – ASDFGerte Feb 11 '21 at 11:43
  • Imho `alert()` is a terrible way to "debug" or log messages. Its blocking behavior can mess with the flow of a function and that necessary interaction (clicking "OK") is cumbersome. Use `console.log()` instead – Andreas Feb 11 '21 at 11:44
  • Not all code paths return a value – Andreas Feb 11 '21 at 11:45
  • 2
    Does this answer your question? [How do I check if a number is a palindrome?](https://stackoverflow.com/questions/199184/how-do-i-check-if-a-number-is-a-palindrome) – angel.bonev Feb 11 '21 at 11:48
  • Btw another big red flag is no `return` in front of the recursive call - which also causes the before mentioned "not all code paths return a value". – ASDFGerte Feb 11 '21 at 11:53
  • Please edit your question to clarify: what do you expect your code to do, and what it is doing instead? – Julian Feb 11 '21 at 17:34
  • Thanks to ASDRGerte for by the answer of sum = aj% 10 but It is not working. For Andreas, Geogebra's JavaScript does not have the console.log () command option so I have to use alert () to debug. – challote Feb 12 '21 at 12:18

0 Answers0