Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding difference of greatest and the smallest digit in a number - JavaScript
We are required to write a JavaScript function that takes in a number and returns the difference between the greatest and the smallest digit present in it.
For example: If the number is 5464676, then the smallest digit here is 4 and the greatest is 7
Hence, our output should be 3
Example
Let's write the code for this function ?
const num = 44353456;
const difference = (num, min = Infinity, max = -Infinity) => {
if(num){
const digit = num % 10;
return difference(Math.floor(num / 10), Math.min(digit, min),
Math.max(digit, max));
};
return max - min;
};
console.log(difference(num));
3
Alternative Approach Using String Conversion
Here's another method that converts the number to a string and uses array methods:
const findDigitDifference = (num) => {
const digits = num.toString().split('').map(Number);
const max = Math.max(...digits);
const min = Math.min(...digits);
return max - min;
};
console.log(findDigitDifference(5464676));
console.log(findDigitDifference(12345));
console.log(findDigitDifference(99999));
3 4 0
How It Works
The recursive approach extracts digits one by one using modulo (%) and integer division. It tracks the minimum and maximum digits encountered, then returns their difference.
The string approach converts the number to a string, splits it into individual digits, and uses built-in Math.max() and Math.min() functions to find the extremes.
Conclusion
Both methods effectively find the difference between the largest and smallest digits in a number. The recursive approach is more memory-efficient, while the string method is more readable and easier to understand.
