📌  相关文章
📜  Java程序检查两个数字是否相互位旋转

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

Java程序检查两个数字是否相互位旋转

给定两个正整数 x 和 y,检查一个整数是否是通过旋转另一个整数得到的。

Input constraint: 0 < x, y < 2^32 

位旋转:旋转(或循环移位)是一种类似于移位的操作,不同之处在于将一端脱落的位放回另一端。
更多关于位旋转的信息可以在这里找到
示例 1:

Input : a = 8, b = 1
Output : yes

Explanation :
Representation of a = 8 : 0000 0000 0000 0000 0000 0000 0000 1000
Representation of b = 1 : 0000 0000 0000 0000 0000 0000 0000 0001
If we rotate a by 3 units right we get b, hence answer is yes

示例 2:

Input : a = 122, b = 2147483678
Output : yes

Explanation :
Representation of a = 122        : 0000 0000 0000 0000 0000 0000 0111 1010
Representation of b = 2147483678 : 1000 0000 0000 0000 0000 0000 0001 1110
If we rotate a by 2 units right we get b, hence answer is yes

由于 x, y > 0 和 x, y < 2^32 可以表示 x 或 y 的总位数为 32。
所以我们需要找到 x 的所有 32 种可能的旋转,并将其与 y 进行比较,直到 x 和 y 不相等。
为此,我们使用一个 64 位的临时变量 x64,它是 x 与 x 连接的结果,即..
x64 的前 32 位与 x 的位相同,后 32 位也与 x64 的位相同。
然后我们继续在右侧将 x64 移位 1,并将 x64 的最右边 32 位与 y 进行比较。
通过这种方式,我们将能够获得由于旋转而产生的所有可能的位组合。
这是上述算法的实现。

Java
// Java program to check if two numbers are bit rotations
// of each other.
class GFG {
 
// function to check if two numbers are equal
// after bit rotation
    static boolean isRotation(long x, long y) {
        // x64 has concatenation of x with itself.
        long x64 = x | (x << 32);
 
        while (x64 >= y) {
            // comparing only last 32 bits
            if (x64 == y) {
                return true;
            }
 
            // right shift by 1 unit
            x64 >>= 1;
        }
        return false;
    }
 
// driver code to test above function
    public static void main(String[] args) {
        long x = 122;
        long y = 2147483678L;
 
        if (isRotation(x, y) == false) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }
}
 
// This code is contributed by 29AjayKumar


输出 :

yes

有关详细信息,请参阅有关检查两个数字是否相互位旋转的完整文章!