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
Rearranging digits to form the greatest number using JavaScript
Problem
We are required to write a JavaScript function that takes in one positive three-digit integer and rearranges its digits to get the maximum possible number.
Approach
To create the maximum number, we need to arrange the digits in descending order. We can convert the number to a string, split it into individual digits, sort them in descending order, and join them back.
Example
Following is the code ?
const num = 149;
const maxRedigit = function(num) {
if(num 999)
return null
return +num
.toString()
.split('')
.sort((a, b) => b - a)
.join('')
};
console.log(maxRedigit(num));
Output
941
How It Works
The function works by:
- First checking if the input is a valid three-digit number (100-999)
- Converting the number to a string using
toString() - Splitting the string into an array of individual digit characters
- Sorting the array in descending order using
sort((a, b) => b - a) - Joining the sorted digits back into a string and converting to number with
+
Enhanced Example with Multiple Test Cases
const maxRedigit = function(num) {
if(num 999) {
return null;
}
return +num
.toString()
.split('')
.sort((a, b) => b - a)
.join('');
};
// Test with different numbers
console.log("Input: 149, Output:", maxRedigit(149));
console.log("Input: 532, Output:", maxRedigit(532));
console.log("Input: 777, Output:", maxRedigit(777));
console.log("Input: 204, Output:", maxRedigit(204));
console.log("Input: 99, Output:", maxRedigit(99)); // Invalid input
Input: 149, Output: 941 Input: 532, Output: 532 Input: 777, Output: 777 Input: 204, Output: 420 Input: 99, Output: null
Conclusion
This solution efficiently rearranges digits to form the maximum possible number by converting to string, sorting digits in descending order, and converting back to number. The function handles validation for three-digit numbers and returns null for invalid inputs.
Advertisements
