Open In App

C++ Program to Generate all rotations of a number

Given an integer n, the task is to generate all the left shift numbers possible. A left shift number is a number that is generated when all the digits of the number are shifted one position to the left and the digit at the first position is shifted to the last.
Examples: 
 

Input: n = 123 
Output: 231 312
Input: n = 1445 
Output: 4451 4514 5144 
 



 

Approach: 
 



Below is the implementation of the above approach: 
 




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to return the count of digits of n
int numberOfDigits(int n)
{
    int cnt = 0;
    while (n > 0) {
        cnt++;
        n /= 10;
    }
    return cnt;
}
  
// Function to print the left shift numbers
void cal(int num)
{
    int digits = numberOfDigits(num);
    int powTen = pow(10, digits - 1);
  
    for (int i = 0; i < digits - 1; i++) {
  
        int firstDigit = num / powTen;
  
        // Formula to calculate left shift
        // from previous number
        int left
            = ((num * 10) + firstDigit)
              - (firstDigit * powTen * 10);
        cout << left << " ";
  
        // Update the original number
        num = left;
    }
}
  
// Driver Code
int main()
{
    int num = 1445;
    cal(num);
    return 0;
}

Output: 
4451 4514 5144

 

Time Complexity: O(log10(num))
Auxiliary Space: O(1)

Please refer complete article on Generate all rotations of a number for more details!


Article Tags :