Reversal of number using java script...i am stuck please help.. i am a beginner

function reverse(num){
let rev_num=0;
while(num>1)
{
rev_num= rev_num*10+num%10;
num=num/10;
}
return rev_num;
}
document.write(reverse(123));
i am getting out put as 324.23
but the actual out put should be 321.

Hello,

There are a few ways to tackle this, such as converting to a string and reversing. Sticking with the approach you are taking, you could change the while loop condition to num > 0, and you’d also need to floor the division inside the loop with Math.floor(num / 10)

The completed code:

function reverse(num) {
  let rev_num = 0;
  while(num > 0) {
    rev_num = rev_num * 10 + num % 10;
    num = Math.floor(num / 10);
  }
  return rev_num;
}
document.write(reverse(123));

Keep in mind, your approach would ignore 0s at the end of a number, which may be what you’re after based on your original code.
For example: document.write(reverse(123000)); would still produce 321

1 Like

thank u that solved my issue :innocent: