![]() |
VOOZH | about |
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 numberN and print the maximum among all the numbers generated. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
765
Time Complexity: O(log10N)
Auxiliary Space: O(1)
Approach:
Initialize a variable max_num with the input number n.
Convert the input number n to a string str_num.
Loop through the indices of the string str_num, starting from index 1 to the end of the string.
Inside the loop, slice the string str_num from index 1 to the end and concatenate it with the first character of the string str_num using the string concatenation operator +.
Convert the resulting rotated string to an integer rotated_num.
Check if rotated_num is greater than max_num, if yes, update max_num to rotated_num.
Return max_num.
Test the function with some inputs and measure the execution time using the time module.
Max Rotation for 657: 765 Max Rotation for 7092: 9270
Time complexity: O(n^2), where n is the number of digits in the input number.
Auxiliary Space: O(n), where n is the number of digits in the input number.