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
Selected Reading
Greater possible digit difference of a number in JavaScript
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.
Example Problem
If the number is 654646, Then the smallest digit here is 4 and the greatest is 6 Hence, our output should be 2
Using Recursive Approach
The recursive solution extracts digits one by one and keeps track of minimum and maximum values:
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));
2
Using String Conversion Approach
A simpler approach converts the number to string and uses array methods:
const maxDifferenceString = (num) => {
const digits = num.toString().split('').map(Number);
const min = Math.min(...digits);
const max = Math.max(...digits);
return max - min;
};
console.log(maxDifferenceString(654646)); // 2
console.log(maxDifferenceString(12345)); // 4 (5-1)
console.log(maxDifferenceString(99999)); // 0 (all same digits)
2 4 0
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Recursive | O(d) | O(d) | Moderate |
| String conversion | O(d) | O(d) | High |
Where d is the number of digits in the input number.
Conclusion
Both approaches solve the problem efficiently. The string conversion method is more readable, while the recursive approach demonstrates mathematical digit extraction techniques.
Advertisements
