GeeksforGeeks » Interview Questions

Adobe Interview Question for Software Engineer/Developer (0 - 2 Years) about Bit Magic

(4 posts)

Tags:

  1. Joy
    guest
    Posted 7 months ago #

    You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e.g., M becomes a substring of N located at i and starting at j).
    EXAMPLE:
    Input: N = 10000000000, M = 10101, i = 2, j = 6
    Output: N = 10001010100

  2. rurouni
    guest
    Posted 7 months ago #

    int mask = 0;
    for (int k = i; k<j; k++) {
      mask |= 1<<k;
    }
    int out = (N & ~mask) | (M << i);
    
  3. Shubhra
    guest
    Posted 4 months ago #

    @ Rurouni, I tried the above example according to your logic. It didn't work correctly. I have programmed a very simple way of solving the above problem, but I think the expected answer would be to use bit manipulation in some way to arrive at the expected result.

    If someone can suggest a bit manipulation technique for the above problem, it would be very helpful...

  4. 5050
    Member
    Posted 2 months ago #

    its simple one line soltion ...

    int out=(N & ~(((1<<(j-i))-1)<<i)) | (M << i );


Reply

You must log in to post.

RSS feed for this topic