VOOZH about

URL: https://www.geeksforgeeks.org/dsa/rotate-bits-of-an-integer/

⇱ Rotate bits of a number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Rotate bits of a number

Last Updated : 26 Apr, 2025

Given a 32-bit integer n and an integer d, rotate the binary representation of n by d positions in both left and right directions. After each rotation, convert the result back to its decimal representation and return both values in an array as [left rotation, right rotation].
Note: 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.  

  • In left rotation, the bits that fall off at left end are put back at right end. 
  • In right rotation, the bits that fall off at right end are put back at left end.

Examples:

Input: n = 28, d = 2
Output: [112, 7]
Explanation: 28 in Binary is: ...0000000000011100. Rotating left by 2 positions, it becomes ...0000000001110000 = 112 (in decimal). Rotating right by 2 positions, it becomes ...0000000000000111 = 7 (in decimal).

Input: n = 29, d = 2
Output: [116, 16391]
Explanation: 29 in Binary is: ...0000000000011101. Rotating left by 2 positions, it becomes ...0000000001110100 = 116 (in decimal). Rotating right by 2 positions, it becomes ...010000000000111 = 16391 (in decimal).

Input: n = 11, d = 10
Output: [11264, 704]

Approach:

One important point to note is, rotating by 32 is equivalent to no rotation, so we take d % 32. For left rotation, we shift the number left and bring the overflowed bits to the right. For right rotation, we shift the number right and bring the lost bits to the left. Finally, we mask the result to ensure it stays within 32 bits.

Steps to implement the above idea:

  • Compute d % 32 to handle unnecessary full rotations.
  • For right rotation, extract the rightmost d bits, shift n right, and place the extracted bits at the leftmost position.
  • Store the right rotated value in the result array after applying a 32-bit mask to keep only valid bits.
  • For left rotation, extract the leftmost d bits, shift n left, and place the extracted bits at the rightmost position.
  • Store the left rotated value in the result array and apply a 32-bit mask to maintain correctness.
  • Return the result array containing the left rotated and right rotated values.

Output
112 7

Time Complexity:O(1) - Only a few bitwise operations.
Space Complexity:O(1) - No extra space except variables. 

Comment
Article Tags: