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 |
Programming is used to solve real-life problems that may include implementing different mathematical formulas. And these formulas are used in various mathematical constants and functions. What is Pi? The Pi is a constant value used in different formulas in geometry like calculating circumference, area, volume, etc. It is...
4 min read
Java is an extremely popular object-oriented programming language for creating different apps. Java's ability to write generic methods is one of its most potent features. Any technique that can be used with several object types is referred to as generic. Developers can design reusable code...
7 min read
A typical problem in computer science is counting pathways in a given matrix that can be solved in a number of ways. In this section, we will discuss three different ways to count path in the given matrix in Java. Problem Statement We have given a 2D...
7 min read
The structure and functionality of two-tier and three-tier database designs are fundamentally different. Before learning about the difference between two-tier and three-tier architecture, let us learn about the two-tier architecture first. The client and the database server. In this case, the client connects directly with the database,...
4 min read
In this section, we are going to discuss what is a zigzag array with proper examples. Also, we will create a Java program to convert a simple or ordinary array into a zigzag array and vice-versa. What is a zigzag array? An array is said to be a...
6 min read
In Java, wait() and notify() are methods provided by the Object class, and they are used for inter-thread communication and synchronization. wait() Method The wait() method is a synchronized method in the Java programming language that causes the current thread to give up the lock on an object...
9 min read
Branching statements are used to change the flow of execution from one section of a program to another. Branching statements are typically utilized within control statements. Java includes three types of branching statements: continue, break, and return. When a given condition is met, we can depart...
7 min read
Java multicasting, also known as typecasting multiple times, refers to the process of applying several typecasting operations sequentially on a variable. This often occurs in scenarios where data types are incompatible but need to be transformed to make the code functional. Multicasting is especially useful in object-oriented...
4 min read
Given a HexaDecimal Number N, converting the number to its corresponding Binary Coded Decimal is the task. Example 1: Input: String str = "2A3" Output: The equivalent BCD is 0010 1010 0011 Explanation: The Binary of 2: 0010 The Binary of A: 1010 The Binary of 3: 0011 Therefore, the equivalent BCD is 0010 1010 0011. Example...
6 min read
The java.time.format.DecimalStyle class has a withPositiveSign() function. The character that represents a positive sign for the Locale of this DecimalStyle in Java is set using the DecimalStyle class interface. With the revised negative sign character, this function returns a DecimalStyle instance when the character is passed...
3 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