Given two positive integers x and y, check if one integer is obtained by rotating bits of other.
Input constraint: 0 < x, y < 2^32
Bit Rotation: A rotation (or circular shift) is an operation similar to shift except that the bits that fall off at one end are put back to the other end.
More information on bit rotation can be found here
Example 1 :
Input : a = 8, b = 1 Output : yes Explanation : Represntation of a = 8 : 0000 0000 0000 0000 0000 0000 0000 1000 Represntation 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
Example 2 :
Input : a = 122, b = 2147483678 Output : yes Explanation : Represntation of a = 122 : 0000 0000 0000 0000 0000 0000 0111 1010 Represntation 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
Since total bits in which x or y can be represented is 32 since x, y > 0 and x, y < 2^32.
So we need to find all 32 possible rotations of x and compare it with y till x and y are not equal.
To do this we use a temporary variable x64 with 64 bits which is result of concatenation of x to x ie..
x64 has first 32 bits same as bits of x and last 32 bits are also same as bits of x64.
Then we keep on shifting x64 by 1 on right side and compare the rightmost 32 bits of x64 with y.
In this way we'll be able to get all the possible bits combination due to rotation.
Here is implementation of above algorithm.
This article is contributed by Pratik Chhajer. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Check if strings are rotations of each other or not | Set 2
- Generating numbers that are divisor of their right-rotations
- Check if all rows of a matrix are circular rotations of each other
- Check whether all the rotations of a given number is greater than or equal to the given number or not
- Count rotations of N which are Odd and Even
- Rotations of a Binary String with Odd Value
- Generate all rotations of a number
- Count rotations divisible by 4
- Count rotations divisible by 8
- Maximum sum of i*arr[i] among all rotations of a given array
- Check if one of the numbers is one's complement of the other
- Check whether bitwise AND of N numbers is Even or Odd
- Check whether bitwise OR of N numbers is Even or Odd
- Check whether product of 'n' numbers is even or odd
- Minimum rotations required to get the same string