Rotate digits of a given number by K
Last Updated :
23 Jul, 2025
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:
Approach to solve this problem is to convert the given number N into a string, and then perform string rotations using substrings and concatenation operations. For left rotation, we can extract the first K digits of the string, and append them to the end of the remaining digits of the string. For right rotation, we can extract the last K digits of the string, and prepend them to the beginning of the remaining digits of the string. Finally, we can convert the resulting rotated string back to an integer and return it as the output.
Here are the steps of approach:
- Convert the given integer N to a string.
- Check whether K is positive or negative. If K is positive, perform a left rotation; otherwise, perform a right rotation.
- For left rotation, extract the first K digits of the string using the substr() function and store it in a new string. Then, extract the remaining digits of the string using substr() and append the first K digits at the end of it using concatenation.
- For right rotation, extract the last K digits of the string using substr() and store it in a new string. Then, extract the remaining digits of the string using substr() and prepend the last K digits at the beginning of it using concatenation.
- Convert the rotated string back to an integer using stoi() function.
- Return the rotated integer as the output.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to rotate the digits of N by K
void rotateNumberByK(int N, int K)
{
// Convert N to a string
string num = to_string(N);
int len = num.length();
// Rotate the string
if(K > 0){
string rotated = num.substr(K) + num.substr(0, K);
cout << stoi(rotated);
}else{
K = abs(K);
string rotated = num.substr(len-K) + num.substr(0, len-K);
cout << stoi(rotated);
}
}
// Driver code
int main()
{
int N = 12345, K = 2;
// Function Call
rotateNumberByK(N, K);
return 0;
}
Java
/*package whatever //do not write package name here */
import java.util.*;
public class GFG {
// Function to rotate the digits of N by K
public static void rotateNumberByK(int N, int K)
{
// Convert N to a string
String num = Integer.toString(N);
int len = num.length();
// Rotate the string
if (K > 0) {
String rotated
= num.substring(K) + num.substring(0, K);
System.out.print(Integer.parseInt(rotated));
}
else {
K = Math.abs(K);
String rotated = num.substring(len - K)
+ num.substring(0, len - K);
System.out.print(Integer.parseInt(rotated));
}
}
// Driver code
public static void main(String[] args)
{
int N = 12345, K = 2;
// Function Call
rotateNumberByK(N, K);
}
}
Python
def rotate_number_by_k(N, K):
# Convert N to a string
num = str(N)
length = len(num)
# Rotate the string
if K > 0:
rotated = num[K:] + num[:K]
print(int(rotated))
else:
K = abs(K)
rotated = num[length - K:] + num[:length - K]
print(int(rotated))
# Driver code
if __name__ == "__main__":
N = 12345
K = 2
# Function Call
rotate_number_by_k(N, K)
C#
using System;
public class GFG {
// Function to rotate the digits of N by K
public static void RotateNumberByK(int N, int K)
{
// Convert N to a string
string num = N.ToString();
int len = num.Length;
// Rotate the string
if (K > 0) {
string rotated
= num.Substring(K) + num.Substring(0, K);
Console.WriteLine(int.Parse(rotated));
}
else {
K = Math.Abs(K);
string rotated = num.Substring(len - K)
+ num.Substring(0, len - K);
Console.WriteLine(int.Parse(rotated));
}
}
// Driver code
public static void Main()
{
int N = 12345, K = 2;
// Function Call
RotateNumberByK(N, K);
}
}
JavaScript
// Function to rotate the digits of N by K
function rotateNumberByK(N, K) {
// Convert N to a string
let num = N.toString();
let len = num.length;
// Rotate the string
if (K > 0) {
let rotated = num.substring(K) + num.substring(0, K);
console.log(parseInt(rotated));
} else {
K = Math.abs(K);
let rotated = num.substring(len - K) + num.substring(0, len - K);
console.log(parseInt(rotated));
}
}
// Driver code
const N = 12345;
const K = 2;
// Function Call
rotateNumberByK(N, K);
Time Complexity: O(N), where N is the number of digits in the given integer.
Space Complexity: O(N), as it involves creating a string representation of the integer and storing it in memory.
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:
C++
// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the count of
// digits in N
int numberOfDigit(int N)
{
// Stores count of
// digits in N
int digit = 0;
// Calculate the count
// of digits in N
while (N > 0) {
// Update digit
digit++;
// Update N
N /= 10;
}
return digit;
}
// Function to rotate the digits of N by K
void rotateNumberByK(int N, int K)
{
// Stores count of digits in N
int X = numberOfDigit(N);
// Update K so that only need to
// handle left rotation
K = ((K % X) + X) % X;
// Stores first K digits of N
int left_no = N / (int)(pow(10, X - K));
// Remove first K digits of N
N = N % (int)(pow(10, X - K));
// Stores count of digits in left_no
int left_digit = numberOfDigit(left_no);
// Append left_no to the right of
// digits of N
N = (N * (int)(pow(10, left_digit))) + left_no;
cout << N;
}
// Driver code
int main()
{
int N = 12345, K = 7;
// Function Call
rotateNumberByK(N, K);
return 0;
}
// The code is contributed by Dharanendra L V
Java
// Java program to implement
// the above approach
import java.io.*;
class GFG {
// Function to find the count of
// digits in N
static int numberOfDigit(int N)
{
// Stores count of
// digits in N
int digit = 0;
// Calculate the count
// of digits in N
while (N > 0) {
// Update digit
digit++;
// Update N
N /= 10;
}
return digit;
}
// Function to rotate the digits of N by K
static void rotateNumberByK(int N, int K)
{
// Stores count of digits in N
int X = numberOfDigit(N);
// Update K so that only need to
// handle left rotation
K = ((K % X) + X) % X;
// Stores first K digits of N
int left_no = N / (int)(Math.pow(10,
X - K));
// Remove first K digits of N
N = N % (int)(Math.pow(10, X - K));
// Stores count of digits in left_no
int left_digit = numberOfDigit(left_no);
// Append left_no to the right of
// digits of N
N = (N * (int)(Math.pow(10, left_digit)))
+ left_no;
System.out.println(N);
}
// Driver Code
public static void main(String args[])
{
int N = 12345, K = 7;
// Function Call
rotateNumberByK(N, K);
}
}
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
C#
// C# program to implement
// the above approach
using System;
class GFG
{
// Function to find the count of
// digits in N
static int numberOfDigit(int N)
{
// Stores count of
// digits in N
int digit = 0;
// Calculate the count
// of digits in N
while (N > 0)
{
// Update digit
digit++;
// Update N
N /= 10;
}
return digit;
}
// Function to rotate the digits of N by K
static void rotateNumberByK(int N, int K)
{
// Stores count of digits in N
int X = numberOfDigit(N);
// Update K so that only need to
// handle left rotation
K = ((K % X) + X) % X;
// Stores first K digits of N
int left_no = N / (int)(Math.Pow(10,
X - K));
// Remove first K digits of N
N = N % (int)(Math.Pow(10, X - K));
// Stores count of digits in left_no
int left_digit = numberOfDigit(left_no);
// Append left_no to the right of
// digits of N
N = (N * (int)(Math.Pow(10, left_digit)))
+ left_no;
Console.WriteLine(N);
}
// Driver Code
public static void Main(string []args)
{
int N = 12345, K = 7;
// Function Call
rotateNumberByK(N, K);
}
}
// This code is contributed by AnkThon
JavaScript
<script>
// Javascript program to implement
// the above approach
// Function to find the count of
// digits in N
function numberOfDigit(N)
{
// Stores count of
// digits in N
let digit = 0;
// Calculate the count
// of digits in N
while (N > 0) {
// Update digit
digit++;
// Update N
N = Math.floor( N / 10);
}
return digit;
}
// Function to rotate the digits of N by K
function rotateNumberByK(N, K)
{
// Stores count of digits in N
let X = numberOfDigit(N);
// Update K so that only need to
// handle left rotation
K = ((K % X) + X) % X;
// Stores first K digits of N
let left_no = Math.floor (N / Math.floor(Math.pow(10,
X - K)));
// Remove first K digits of N
N = N % Math.floor(Math.pow(10, X - K));
// Stores count of digits in left_no
let left_digit = numberOfDigit(left_no);
// Append left_no to the right of
// digits of N
N = (N * Math.floor(Math.pow(10, left_digit)))
+ left_no;
document.write(N);
}
// Driver Code
let N = 12345, K = 7;
// Function Call
rotateNumberByK(N, K);
// This code is contributed by souravghosh0416.
</script>
Time Complexity: O(log10N)
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem