Open In App

Javascript Program to Generate all rotations of a number

Last Updated : 13 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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: 
 

Javascript




<script>
 
    // Javascript implementation of the approach
     
    // Function to return the count of digits of n
    function numberOfDigits(n)
    {
        let cnt = 0;
        while (n > 0) {
            cnt++;
            n = parseInt(n / 10, 10);
        }
        return cnt;
    }
 
    // Function to print the left shift numbers
    function cal(num)
    {
        let digits = numberOfDigits(num);
        let powTen = Math.pow(10, digits - 1);
 
        for (let i = 0; i < digits - 1; i++) {
 
            let firstDigit = parseInt(num / powTen, 10);
 
            // Formula to calculate left shift
            // from previous number
            let left = ((num * 10) + firstDigit)
                - (firstDigit * powTen * 10);
            document.write(left +  " ");
 
            // Update the original number
            num = left;
        }
    }
     
    let num = 1445;
    cal(num);
     
</script>


Output: 

4451 4514 5144

 

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

Approach: 

  • Assume n = 123 
  • let temp = str(n) + str(n) i.e 123123
  • Now iterate through the temp and take slice 3 digits from iterating index of temp which is 231.
  • Iterate through temp till the iterator is less than the half of length of temp.

Below is the implementation of above approach: 

Javascript




<script>
 
// Function to print the left shift numbers
    function cal(num)
    {  
      var temp  = '' + num
      var len = temp.length
     temp += temp;
    for( let i = 1 ; i*2 <temp.length ; i++){
            console.log(temp.slice(i , i + len ))
    }
      
    }
      
    let num = 1445;
    cal(num);
 </script>


Output:

4451
4514
5144

Time Complexity: O(n)
Auxiliary Space: O(n)

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads