Java Program to Rotate digits of a given number by K
Given two integers N and K, the task is to rotate the digits of N by K. If K is a positive integer, left rotate its digits. Otherwise, right rotate its digits.
Examples:
Input: N = 12345, K = 2
Output: 34512Â
Explanation:Â
Left rotating N(= 12345) by K(= 2) modifies N to 34512.Â
Therefore, the required output is 34512
Input: N = 12345, K = -3
Output: 34512Â
Explanation:Â
Right rotating N(= 12345) by K( = -3) modifies N to 34512.Â
Therefore, the required output is 34512
Approach: Follow the steps below to solve the problem:
- Initialize a variable, say X, to store the count of digits in N.
- Update K = (K + X) % X to reduce it to a case of left rotation.
- Remove the first K digits of N and append all the removed digits to the right of the digits of N.
- Finally, print the value of N.
Below is the implementation of the above approach:
Java
import java.io.*;
class GFG {
static int numberOfDigit( int N)
{
int digit = 0 ;
while (N > 0 ) {
digit++;
N /= 10 ;
}
return digit;
}
static void rotateNumberByK( int N, int K)
{
int X = numberOfDigit(N);
K = ((K % X) + X) % X;
int left_no = N / ( int )(Math.pow( 10 ,
X - K));
N = N % ( int )(Math.pow( 10 , X - K));
int left_digit = numberOfDigit(left_no);
N = (N * ( int )(Math.pow( 10 , left_digit)))
+ left_no;
System.out.println(N);
}
public static void main(String args[])
{
int N = 12345 , K = 7 ;
rotateNumberByK(N, K);
}
}
|
Time Complexity: O(log10N)
Auxiliary Space: O(1)
Please refer complete article on Rotate digits of a given number by K for more details!
Last Updated :
27 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...