Computer >> Computer tutorials >  >> Programming >> Javascript

Difference between a number and its reversed number JavaScript


We are required to write a JavaScript function that takes in a number as the first and the only argument.

The function should −

  • calculate the reversed number for the argument.
  • return the absolute difference between the original number and the reversed number.

For example −

If the input number is −

const num = 45467;

Then the reversed number will be − 76454

And the output should be 76454 - 45467 = 30987

Example

const num = 45467;
const findReversed = (num, res = 0) => {
   if(num){
      return findReversed(Math.floor(num / 10), (res * 10) + (num % 10));
   };
   return res;
};
const findDifference = num => {
   const reversed = findReversed(num);
   const difference = Math.abs(num - reversed);
   return difference;
};
console.log(findDifference(num));

Output

And the output in the console will be−

30987