

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding the maximum number using at most one swap in JavaScript
We are required to write a JavaScript function that takes in a number as the first and the only argument.
The task of our function is to perform at most one swap between any two digits of the number and yield the maximum possible number. If, however, the number is already the maximum possible number we should return the number itself.
For example −
If the input number is −
const num = 1625;
Then the output should be −
const output = 6125;
We swapped 1 and 6 and this is the only swap the yields the greatest number in single swap
Example
The code for this will be −
const num = 1625; const findMaximumDigit = (num, max = 0) => { if(!num){ return max; }; return findMaximumDigit(Math.floor(num / 10), Math.max(max, num %10)); }; const makeOneSwap = (num = 1) => { let i = 0; const max = findMaximumDigit(num); const numStr = String(num); const numArr = numStr.split(''); const maxIndex = numStr.lastIndexOf('' + max); while(i < maxIndex){ if(+numStr[i] < max){ let temp = numArr[i]; numArr[i] = numArr[maxIndex]; numArr[maxIndex] = temp; break; }; }; return +(numArr.join('')); }; console.log(makeOneSwap(num));
Output
And the output in the console will be −
6125
- Related Questions & Answers
- Form the largest number using at most one swap operation C++
- Form the smallest number using at most one swap operation in C++
- Forming palindrome using at most one deletion in JavaScript
- Smallest number formed by shuffling one digit at most in JavaScript
- Maximum sum subarray removing at most one element in C++
- Maximum number of fixed points using at most 1 swaps in C++
- Maximize the maximum subarray sum after removing at most one element in C++
- Finding one missing number in a scrambled sequence using JavaScript
- JavaScript Finding the third maximum number in an array
- Finding maximum number from two arrays in JavaScript
- Finding the most frequent word(s) in an array using JavaScript
- Finding the third maximum number within an array in JavaScript
- Finding number of occurrences of the element appearing most number of times in JavaScript
- Finding the second most frequent character in JavaScript
- Next higher number using atmost one swap operation in C++
Advertisements