What does the following Java function perform? (Assume int occupies four bytes…
2018
What does the following Java function perform? (Assume int occupies four bytes of storage)
public static int f(int a)
{ // Pre-conditions : a > 0 and no oveflow/underflow occurs
int b=0;
for (int i=0; i<32; i++)
{
b = b<<1;
b=b | ( a & 1);
a=a >>>1; // This is a logical shift
}
return b;
}
- A.
Returns the int that has the binary representation of integer a.
- B.
Return the int that has reversed binary representation of integer a.
- C.
Return the int that represents the number of 1’s in the binary representation of integer a.
- D.
Return the int that represents the number of 0’s in the binary representation of integer a.
Attempted by 122 students.
Show answer & explanation
Correct answer: B
Key idea: The function returns an integer whose 32-bit binary representation is the bitwise reverse of the input integer a.
Initialization: b is set to 0.
Loop body (repeated 32 times): shift b left by 1, copy the least significant bit of a into b (using b = b | (a & 1)), then perform a logical right shift on a (a >>>= 1).
Effect: after i iterations the i-th least significant bit of the original a has been moved to the (31 - i)-th position of b, so after 32 iterations all bits are reversed.
Example:
Input a = 13 has 32-bit representation 00000000000000000000000000001101.
Resulting b is 10110000000000000000000000000000, which as an unsigned 32-bit number is 2952790016 (as a signed 32-bit int this is -1342177280).
Notes:
The code performs a full 32-bit reversal. Leading zeros in the original value become trailing zeros in the result.
Using the logical right shift (>>>) ensures zeros are shifted in from the left; the routine treats bit positions rather than signed magnitude.
Time complexity is fixed: 32 iterations, i.e., O(1).
A video solution is available for this question — log in and enroll to watch it.