Python3 Program to Rotate digits of a given number by K
Last Updated :
06 Sep, 2024
INTRODUCTION:
One important point to consider when working with the algorithm to rotate the digits of a given number by k positions is the time complexity.
If we were to implement this algorithm using the approach shown in the previous example, the time complexity would be O(n), where n is the number of digits in the input number. This is because the algorithm must iterate through each digit of the number to perform the rotation.
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:
Python
# Python3 program to implement
# the above approach
# Function to find the count of
# digits in N
def numberOfDigit(N):
# Stores count of
# digits in N
digit = 0
# Calculate the count
# of digits in N
while (N > 0):
# Update digit
digit += 1
# Update N
N //= 10
return digit
# Function to rotate the digits of N by K
def rotateNumberByK(N, K):
# Stores count of digits in N
X = numberOfDigit(N)
# Update K so that only need to
# handle left rotation
K = ((K % X) + X) % X
# Stores first K digits of N
left_no = N // pow(10, X - K)
# Remove first K digits of N
N = N % pow(10, X - K)
# Stores count of digits in left_no
left_digit = numberOfDigit(left_no)
# Append left_no to the right of
# digits of N
N = N * pow(10, left_digit) + left_no
print(N)
# Driver Code
if __name__ == '__main__':
N, K = 12345, 7
# Function Call
rotateNumberByK(N, K)
# This code is contributed by mohit kumar 29
Time Complexity: O(log10N)
Auxiliary Space: O(1)
EXAMPLE 2:
Python
def rotate_digits(num, k):
# convert number to string and store in a list
num_list = [c for c in str(num)]
# rotate the list by k
num_list = num_list[k:] + num_list[:k]
# convert the list back to a number and return it
return int(''.join(num_list))
# test the function
print(rotate_digits(12345, 2)) # output: 34512
print(rotate_digits(12345, 4)) # output: 23451
print(rotate_digits(12345, 6)) # output: 12345
This code defines a function rotate_digits that takes an integer num and an integer k as input. It first converts the number to a string and stores the individual digits in a list. It then rotates the list by k positions using slicing, and converts the rotated list back to a number using join. The resulting rotated number is returned by the function.
The function is then called with several test cases to demonstrate its behavior.
This implementation uses modulo and integer division operations to separate the digits of the number into two parts, and then combines them in the appropriate order to form the rotated number. Since these operations are O(1), the overall time complexity of the algorithm is also O(1).
Please refer complete article on Rotate digits of a given number by K for more details!
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read