Given a 32-bit integer n, shift all set bits (1s) to the leftmost positions while keeping their count.
In other words, count the number of 1 bits in the 32-bit binary representation of n, then return the integer formed by placing that many 1 bits starting from the most significant bit (bit 31), with all remaining bits set to 0.
Return the resulting 32-bit unsigned integer.
Function Signature
def set_bit_shift(n: int) -> int:
Rules
-
n
is read as an unsigned 32-bit value, and only its 32 bits count.
-
The result is also an unsigned 32-bit value, between 0 and 4294967295. When
n
has bit 31 set in the result, return the large positive number, never a negative one.
-
If
n
has no set bits, the result is 0.
Constraints
Examples
Input: n = 13
Output: 3758096384
13 in 32-bit binary is 00000000000000000000000000001101, which has 3 set bits. Placing them at bits 31, 30 and 29 gives 11100000000000000000000000000000, which is 3758096384.
Input: n = 255
Output: 4278190080
255 is 00000000000000000000000011111111, which has 8 set bits. Moving all 8 to the top gives 11111111000000000000000000000000, which is 4278190080.
Input: n = 0
Output: 0
There are no set bits to place, so every bit of the result is 0.