📜  Java程序将给定数字的数字旋转K

📅  最后修改于: 2022-05-13 01:55:16.192000             🧑  作者: Mango

Java程序将给定数字的数字旋转K

给定两个整数NK ,任务是将N的数字旋转 K。如果K是正整数,则左旋转其数字。否则,右旋转它的数字。

例子:

解决方法:按照以下步骤解决问题:

  • 初始化一个变量,比如X ,以存储N中的位数。
  • 更新K = (K + X) % X以将其减少为左旋转的情况。
  • 删除N的前K个数字,并将所有删除的数字附加到N的数字的右侧。
  • 最后,打印N的值。

下面是上述方法的实现:

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);
    }
}


输出:
34512

时间复杂度: O(log 10 N)
辅助空间: O(1)

有关详细信息,请参阅有关将给定数字的数字旋转 K 的完整文章!