Redirecting to

Copy Set Bits In A Range

Try First, Check Solution later

1. You should first read the question and watch the question video.
2. Think of a solution approach, then try and submit the question on editor tab.
3. We strongly advise you to watch the solution video for prescribed approach.

1. You are given two numbers A and B.
2. You are given two more numbers left and right, representing a range [left,right].
3. You have to set bits in B which are set in A lying in the above mentioned range.
4. Print the updated number B.
Input Format
4 numbers representing A,B,left and right.
Output Format
A number
Question Video
-10^9 <= A,B <= 10^9
1 < left < right < 32
Sample Input
Sample Output

  • Editorial

    The problem states that we are provided with two numbers say A and B and we are also provided with valid index positions for integer A. These positions are bit positions for the 4-byte integer. The task is to update the bits which are set in this range in integer A to B and then return the updated B.

    Let us take an example to understand the problem better:

    A = 10 -> 1 0 1 0

    Index ->  4 3 2 1 {Index positions provided in the question are 1 based}

    B = 13 -> 1 1 0 1

    leftPos = 2

    rightPos = 3

    In the range of leftPos <= k <= rightPos at k = 2 there is a set bit so we update the B integer and we get,

    B = 15 -> 1 1 1 1

    To implement the solution we need to traverse every bit position from leftPos to rightPos and for every position we will have to make a mask and then check whether the bit of integer A is set at this position or not, if true then we will be updating B integer else we will continue the iteration for the next position.

    Time Complexity: O(k)

    The time complexity for the function is proportional to the range of index to traverse.

    Space Complexity: O(1)

    The space complexity for the function is constant.

  • Asked in Companies
  • Related Topics

Video Solution

Code Solution

Id Name