1283. Reverse All Bits of an Integer

EasyBit ManipulationBit ManipulationBit ReversalShift

Given a non-negative integer n and a width bits, reverse the order of the lowest bits bits of n and return the resulting value. The classic 32-bit reversal is the special case bits = 32. Bit 0 swaps with bit (bits-1), bit 1 with bit (bits-2), and so on.

Input: A JSON object {"n": <integer>, "bits": <width>} with 1 <= bits <= 32 and 0 <= n < 2^bits.

Output: Return the bit-reversed value within the given width.

Examples

Example 1
Input: {"n":3,"bits":4}
Output: 12
Explanation: 0011 reversed within 4 bits is 1100 = 12.
Example 2
Input: {"n":1,"bits":8}
Output: 128
Explanation: 00000001 reversed within 8 bits is 10000000 = 128.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →