GeeksforGeeks » Interview Questions
Adobe Interview Question for Software Engineer/Developer (0 - 2 Years) about Bit Magic
(4 posts)-
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 -
int mask = 0; for (int k = i; k<j; k++) { mask |= 1<<k; } int out = (N & ~mask) | (M << i); -
@ 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...
-
its simple one line soltion ...
int out=(N & ~(((1<<(j-i))-1)<<i)) | (M << i );
Reply
You must log in to post.