Javascript Program to Find Maximum value possible by rotating digits of a given number
Last Updated :
10 Feb, 2022
Given a positive integer N, the task is to find the maximum value among all the rotations of the digits of the integer N.
Examples:
Input: N = 657
Output: 765
Explanation: All rotations of 657 are {657, 576, 765}. The maximum value among all these rotations is 765.
Input: N = 7092
Output: 9270
Explanation:
All rotations of 7092 are {7092, 2709, 9270, 0927}. The maximum value among all these rotations is 9270.
Approach: The idea is to find all rotations of the number N and print the maximum among all the numbers generated. Follow the steps below to solve the problem:
- Count the number of digits present in the number N, i.e. upper bound of log10N.
- Initialize a variable, say ans with the value of N, to store the resultant maximum number generated.
- Iterate over the range [1, log10(N) – 1] and perform the following steps:
- Update the value of N with its next rotation.
- Now, if the next rotation generated exceeds ans, then update ans with the rotated value of N
- After completing the above steps, print the value of ans as the required answer.
Below is the implementation of the above approach:
Javascript
<script>
function findLargestRotation(num)
{
let ans = num;
let len = Math.floor(Math.log10(num) + 1);
let x = Math.pow(10, len - 1);
for (let i = 1; i < len; i++) {
let lastDigit = num % 10;
num = parseInt(num / 10);
num += (lastDigit * x);
if (num > ans) {
ans = num;
}
}
document.write(ans);
}
let N = 657;
findLargestRotation(N);
</script>
|
Time Complexity: O(log10N)
Auxiliary Space: O(1)
Please refer complete article on Maximum value possible by rotating digits of a given number for more details!
Share your thoughts in the comments
Please Login to comment...