Rotate Bits Problem in Java6 May 2025 | 7 min read The Rotate Bits problem involves shifting the bits of an integer to the left or right, wrapping the overflowed bits to the opposite end. This operation is crucial in low-level programming, cryptography, and data manipulation tasks. Java provides bitwise operators to implement this efficiently for both signed and unsigned numbers. ExampleInput: Number = 19 (Binary: 10011), Rotate Left by 2 bits. Output: Rotate Left Result: 14 Input: Number = 19 (Binary: 10011), Rotate Right by 2 bits. Output: Rotate Right Result: 28 ExplanationIn the example, rotating 19 (binary 10011) left by 2 bits results in 14 (binary 01110), as the overflow bits 11 wraps around. Similarly, rotating 19 right by 2 bits gives 28 (binary 11100), as the overflow bits 11 moves to the left end. Bitwise Rotation ApproachStep 1: Understand the Inputs: Number: The integer whose bits need to be rotated (for example, 19, which is 10011 in binary). Bit Length: The number of bits to consider during rotation (for example, 5 bits for simplicity). Rotation Amount: The number of positions to shift the bits (for example, 2 positions). Step 2: Rotate Left: Left Shift: Shift the bits of the number to the left by the rotation amount (number << rotation). Example: Shifting 10011 left by 2 gives 1001100. Extract Overflow Bits: Compute the bits that "fall off" the left side during the shift by right-shifting the original number (number >>> (bit_length - rotation)). Example: Shifting 10011 right by 3 gives 00010. Step 2. 1: Combine the Results: Use the bitwise OR operator to merge the left-shifted result with the overflow bits. Example: Combining 1001100 with 00010 gives 1001100. Constrain to Bit Length: If the result exceeds the bit length, mask it using (1 << bit_length) - 1 to ensure only the required bits are retained. Step 3: Rotate Right: Right Shift: Shift the bits of the number to the right by the rotation amount (number >>> rotation). Example: Shifting 10011 right by 2 gives 00100. Extract Overflow Bits: Compute the bits that "fall off" the right side during the shift by left-shifting the original number (number << (bit_length - rotation)). Example: Shifting 10011 left by 3 gives 1000000. Step 4: Combine the Results: Use the bitwise OR operator to merge the right-shifted result with the overflow bits. Example: Combining 00100 with 1000000 gives 1000011. Constrain to Bit Length: Mask the result to ensure only the required number of bits are retained. Step 4. 1: Verify the Results: After performing the bit rotations, it's important to verify the results by comparing the rotated values with the expected output. It can be done by converting the binary result back to decimal and ensuring it matches the expected outcome. Testing with various inputs will help ensure accuracy and correctness of the algorithm. Step 5: Output the Results: After performing the left and right bit rotations, display the final results for both operations. Ensure the results are within the specified bit length by masking them if necessary. The final output will show the rotated integer values, demonstrating the effect of shifting the bits left and right. File Name: RotateBits.java Output: Rotate Left Result: 14 Rotate Right Result: 28 Complexity AnalysisTime ComplexityThe time complexity of the bit rotation algorithm is O(1). It is because each rotation operation involves a constant number of bitwise operations (shift and mask), which take constant time regardless of the size of the number or the rotation amount. Thus, the algorithm executes in continuous time. Space ComplexityThe space complexity of the bit rotation algorithm is O(1). The algorithm only requires a fixed amount of space for storing the input number, bit length, and intermediate results during the rotations. It uses no additional data structures or memory that grows with the input size. Effective Rotation with Modular Arithmetic ApproachAlgorithmBit Length: The number of bits to consider for the rotation (for example, 5). Rotation Amount: The number of positions to shift the bits (for example, 2). Step 1: Understand the Problem Number: The integer whose bits need to be rotated (for example, 19, binary 10011). Bit Length: The number of bits to consider for the rotation (for example, 5). Rotation Amount: The number of positions to shift the bits (for example, 2). It involves: Shifting the bits of the number left or right by the rotation amount. Wrapping any bits that overflow to the opposite end. Step 2: Handle the Rotation Amount: The rotation amount may exceed the bit length. For example, rotating 5 bits by 7 positions is equivalent to rotating by 7 % 5 = 2 positions. Effective Rotation = rotation % bitlength. Use the modulus operator to calculate the effective rotation: Effective Rotation = rotation % bitlength. Step 2. 1: Determine the Rotation Direction: After calculating the effective rotation, decide whether to perform a left rotation or a right rotation based on the requirement. Each direction involves specific bit manipulations: Left Rotation: Shifts bits to the left while wrapping overflow bits to the rightmost positions. Right Rotation: Shifts bits to the right while wrapping overflow bits to the leftmost positions. Step 3: Rotate Left: Shift Left: Shift the number's bits left by the effective rotation amount. Use the left-shift operator (<<). For example, shifting 19 (10011) left by 2 produces 1001100. Extract Overflow Bits: The overflow bits are the bits that move out of the leftmost end during the shift. Compute these bits by right-shifting the original number by (bitLength - effective Rotation). Use the unsigned right-shift operator (>>>). For example, shifting 19 (10011) right by 3 gives 00010. Wrap Around: Combine the left-shifted number and the overflow bits using the bitwise OR operator(I) For example, combining 1001100 and 00010 gives 1001110. Step 3. 1: Mask to Fit Bit Length: Apply a bitwise mask to ensure the result fits within the specified bit length. The mask is (1 << bitLength) - 1, which creates a binary number with only the required bits set to 1. For example, for 5 bits, the mask is 11111. Applying it ensures only the first 5 bits are kept. Step 4: Rotate Right Shift Right: Shift the number's bits right by the effective rotation amount. Use the unsigned right-shift operator (>>>). For example, shifting 19 (10011) right by 2 gives 00100. Extract Overflow Bits: The overflow bits are the bits that move out of the rightmost end during the shift. Compute these bits by left-shifting the original number by (bit Length - effective Rotation). Use the left-shift operator (<<). For example, shifting 19 (10011) left by 3 gives 1000000. Wrap Around: Combine the right-shifted number and the overflow bits using the bitwise OR operator (|). For example, combining 00100 and 1000000 gives 1000011. Step 4. 1: Mask to Fit Bit Length: Apply the bitwise mask (1 << bitLength) - 1 to keep the result within the specified bit length. Step 5: Verify the Results: Convert the final binary result back to decimal to confirm correctness. Test with different input values to ensure the implementation works consistently. Step 6: Optimize for Edge Cases: Handle special cases to ensure robustness: Zero Rotation: If the rotation amount is 0, the number remains unchanged. Skip rotation logic for this case. Full Cycle Rotation: When the rotation amount is a multiple of the bit length (for example, rotating 5 bits by 5 or 10 positions), the number remains unchanged. Avoid unnecessary computations. Input Validation: Ensure the inputs are valid, such as checking if the bit length matches the binary representation of the number or if the rotation amount is non-negative. File Name: RotateBitsAlt.java Output: Rotate Left Result: 14 Rotate Right Result: 28 Complexity AnalysisTime ComplexityThe time complexity of the bit rotation algorithm is O(1) since it performs a fixed number of bitwise operations-shifting, masking, and combining-regardless of the size of the input. These operations execute in constant time, making the algorithm efficient and independent of the number of bits being rotated. Space Complexity The space complexity of the bit rotation algorithm is O(1). It uses a constant amount of memory to store the input number, bit length, rotation value, and intermediate results. No additional data structures are required, as all operations are performed in place using bitwise operators, ensuring minimal memory usage. Next TopicPower of a Number in Java |
How to Swap or Exchange Objects in Java
In Java, swapping or exchanging objects can be done by assigning one object's value to another object and vice versa. It can be done by using a temporary variable to hold the value of one object while it is being swapped with the value of another...
5 min read
Sorting a Java Vector in Descending Order Using Comparator
Introduction: A dynamic array-like data structure that lets you store and work with objects is the Java Vector class. Sorting the components of a Vector in a precise order might often be necessary, whether you are working on a small project or a large-scale application. In this...
3 min read
Number of digits in N factorial to the power N in Java
In Java, finding the number of digits in N factorial raised to the power of N is a fascinating puzzle. As N increases, the resulting number can become large, requiring careful handling. The task involves counting how many digits are in the final result and calls...
5 min read
Get Yesterday's Date in Milliseconds Java
There are numerous techniques in Java to obtain the millisecond value of yesterday's date. Method 1: Using java.util.Calendar The Java.util.Date class and the Java.util.The Java legacy date and time API includes calendar classes. Although these classes are still accessible in Java, the more recent java.time package has mostly...
5 min read
Java Clone Examples
Object cloning indicates the production of a precise duplicate of an article. It makes another occurrence of the class of the ongoing article and introduces every one of its fields with the very items in the comparing fields of this item. Utilizing Assignment Operator to make a...
12 min read
Delegation Event Model in Java
The Delegation Event model is defined to handle events in GUI programming languages. The GUI stands for Graphical User Interface, where a user graphically/visually interacts with the system. The GUI programming is inherently event-driven; whenever a user initiates an activity such as a mouse activity, clicks, scrolling,...
7 min read
Java 9 Interface Private Methods
Java 9 Private Interface Methods In Java 9, we can create private methods inside an interface. Interface allows us to declare private methods that help to share common code between non-abstract methods. Before Java 9, creating private methods inside an interface cause a compile time error. The following...
1 min read
Tree Boundary Traversal in Java
Tree Boundary Traversal is a specialized technique in binary tree traversal where nodes are visited in a specific order to cover the outer boundary of the tree. In this traversal, we aim to visit nodes that lie on the periphery of the tree, including the left...
15 min read
Java SortedSet E Interface
Java SortedSet<E> Interface The SortedSet<E> interface in Java is part of the Java Collections Framework and provides a collection of unique elements, where the elements are stored in sorted order. It extends the Set<E> interface. It was introduced in Java 2 and has been an essential...
9 min read
Extravagant Number in Java
In this section, we will learn what is extravagant number and also create Java programs to check if the given number is an extravagant number or not. The extravagant number Java program frequently asked in Java coding interviews and academics. Extravagant Number A natural number that has fewer...
4 min read
We request you to subscribe our newsletter for upcoming updates.

We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India