Monday, November 18, 2024
Google search engine
HomeLanguagesPython3 Program to Generate all rotations of a number

Python3 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: 
 

  • Assume n = 123.
  • Multiply n with 10 i.e. n = n * 10 = 1230.
  • Add the first digit to the resultant number i.e. 1230 + 1 = 1231.
  • Subtract (first digit) * 10k from the resultant number where k is the number of digits in the original number (in this case, k = 3).
  • 1231 – 1000 = 231 is the left shift number of the original number.

Below is the implementation of the above approach: 
 

Python3




# Python3 implementation of the approach
 
# function to return the count of digit of n
def numberofDigits(n):
    cnt = 0
    while n > 0:
        cnt += 1
        n //= 10
    return cnt
     
# function to print the left shift numbers
def cal(num):
    digit = numberofDigits(num)
    powTen = pow(10, digit - 1)
     
    for i in range(digit - 1):
         
        firstDigit = num // powTen
         
        # formula to calculate left shift
        # from previous number
        left = (num * 10 + firstDigit -
               (firstDigit * powTen * 10))
        print(left, end = " ")
         
        # Update the original number
        num = left
         
# Driver code
num = 1445
cal(num)
 
# This code is contributed
# by Mohit Kumar


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!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
You’ll access excellent video content by our CEO, Sandeep Jain, tackle common interview questions, and engage in real-time coding contests covering various DSA topics. We’re here to prepare you thoroughly for online assessments and interviews.
Ready to dive in? Explore our free demo content and join our DSA course, trusted by over 100,000neveropen! Whether it’s DSA in C++, Java, Python, or JavaScript we’ve got you covered. Let’s embark on this exciting journey together!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments