Greater possible digit difference of a number in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

JavaScript for beginners

Best Seller

74 Lectures 10 hours

Modern Javascript for Beginners + Javascript Projects

Most Popular

112 Lectures 15 hours

The Complete Full-Stack JavaScript Course!

Best Seller

96 Lectures 24 hours

We are required to write a JavaScript function that takes in a number. Then the function should return the greatest difference that exists between any two digits of the number.

In other words, the function should simply return the difference between the greatest and the smallest digit present in it.

For example:

If the number is 654646,
Then the smallest digit here is 4 and the greatest is 6
Hence, our output should be 2

Example

The code for this will be −

const num = 654646;
const maxDifference = (num, min = Infinity, max = -Infinity) => {
if(num){
const digit = num % 10;
return maxDifference(Math.floor(num / 10), Math.min(digit, min),
Math.max(digit, max));
};
return max - min;
};
console.log(maxDifference(num));

Output

The output in the console −

2
Updated on 15-Oct-2020 09:07:04