0

Why does this work in Java but not in JavaScript? I tried using this in Java and its working perfectly fine but I can't figure out why it's only printing "Not a palindrome" in JavaScript? thank you

 var n = 121;
 var sum = 0, r;
 var temp = n;    
 while(n>0)
   {    
    r = n % 10;   
    sum = (sum*10)+r;    
    n = n/10;    
   }    
  if(temp==sum)    
    console.log("It is a Palindrome number.");
  else  
    console.log("Not a palindrome");   

2 Answers2

4

You're using floating point division when you want floor division(aka integer division), since JS numbers are always floating point. To fix it, use Math.floor after the division:

var n = 121;
var sum = 0
var r;
var temp = n;    
while(n > 0){    
    r = n % 10;   
    sum = (sum * 10) + r;    
    n = Math.floor(n / 10);    
}
if(temp == sum){
    console.log("It is a palindrome number.");
}else{
    console.log("Not a palindrome");
}
SuperStormer
  • 4,997
  • 5
  • 25
  • 35
2

The reason this code does not same exact results in both java and javascript is because of difference in data types.

You are (most likely) declaring vars in java like:

int n = 121;    // this is strictly an integer

Whereas when you declare in javascript:

var n = 121;    // this is interpreted according to the calculation where used

So in java, n/10 will give you an integer, a round value integer answer. See this answer: https://stackoverflow.com/a/37795340/7892830

But in javascript, n/10 may give you a decimal value. Which is where your program is failing.

Solution: Use proper Math.ceil() or floor() function in javascript so it gets rounded to the nearest integer value. I'll let you figure out which one you need in this case.

singh.rbir
  • 85
  • 1
  • 8