FunctionRacerProblemsRace

Insert a Bit Field

MediumBitsPython, JavaScript, TypeScript, Java, C++

n is a 32 bit unsigned number whose bits are numbered from the right, bit 0 being the lowest. Clear the bits of n at positions lo through hi (both ends included) and write the bits of m into that gap: bit 0 of m goes to position lo, bit 1 of m to position lo + 1, and so on up to position hi. Bits of n outside the gap keep their values. m always fits in the gap. Return the resulting number as a non-negative integer; because hi can be 31, it can be as large as 2**32 - 1.

Example 1

n 1024
m 19
lo 2
hi 6
returns 1100

1024 is 10000000000; bits 2 to 6 are cleared (they were 0 already) and 19, which is 10011, is written there, giving 10001001100, or 1100.

Example 2

n 255
m 0
lo 2
hi 5
returns 195

255 is 11111111; clearing bits 2 to 5 leaves 11000011, which is 195, and m is 0 so nothing is added.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Bits problems