Copy set bits in a given range from one number to another

Easy

Problem

For every bit position from l to r (1-indexed from the right) that is set in y, set the same bit in x. Return the new x.

Example 1

Input:  x = 44 (101100), y = 3 (000011), l = 1, r = 5
Output: 47 (101111)

Also asked as: Copy set bits in a range

Test cases

Case 1

Input:    44, 3, 1, 5
Expected: 47

Case 2

Input:    10, 13, 2, 3
Expected: 14

Case 3

Input:    0, 7, 1, 3
Expected: 7

Case 4

Input:    8, 7, 4, 4
Expected: 8

Your solution ✓ Solved

Ctrl/⌘ + Enter to run
View solutionHide solution1 approach

1. Build a range mask and OR

Time O(1)Space O(1)

mask = bits [l..r] set. result = x | (y & mask) — copies y’s bits in that range into x.

function copyBitsInRange(x, y, l, r) {
let mask = 0;
for (let i = l; i <= r; i++) mask |= (1 << (i - 1)); // 1-indexed positions
return x | (y & mask);
}