Insert a Bit Field
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
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
255 is 11111111; clearing bits 2 to 5 leaves 11000011, which is 195, and m is 0 so nothing is added.
Constraints
0 <= n < 2**310 <= lo <= hi <= 310 <= m < 2(hi - lo + 1)andm < 231
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Bits problems
- Longest Pair With No Shared LetterMedium
- Next Gray CodeMedium
- Subsets With a Target XORMedium
- The One Not TripledMedium
- Two Unpaired NumbersMedium
- Undo the XOR ChainMedium
- Well-Formed Byte StreamMedium
- A Different Hat for EveryoneHard