Javascript 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 34512Input: 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:
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> |
Output:Â
34512
Â
Time Complexity: O(log10N)
Auxiliary Space: O(1)
Please refer complete article on Rotate digits of a given number by K 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.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



