For I have a coming technical interview, I start to study the book "Cracking the Coding Interview" recently.
When I was practicing the question of 5.1, I found the solution of the book is different from mine.
The question is:
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 (eg, 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
The solution is:
public static int updateBits2(int n, int m, int i, int j) {
int max = ~0;
int left = max - ((1 << j) - 1);
int right = (1 << i) - 1;
int mask = left | right;
int maskN = mask & n;
int result = maskN | (m << i);
return result;
}
The key point is to create a mask to set the bit from i to j of n to 0, and left shift m to i position and OR the m and n.
When the input is n=89, m=3, i=2, j=4, the answer should be 77, for:
n = 1011001
m = 011
n with 2 to 4 set by m = 1001101 = 77
but the result of the solution is 93.
Then I found out that the mask create by the solution lacks one 0 bit in the left side. For example, the mask should be 1100011 with the given inputs above. But the mask created by the solution is 1110011.
I fix this by change this line
int left = max - ((1 << j) - 1);
to
int left = max - ((1 << j + 1) - 1);
So my question is, is the solution wrong or do I miss something?
You can tell by the EXAMPLE, where i=2, j=6, and 5 bits are changed, that [i,j] is meant to be an inclusive range. So if you have i=2 and j=4, you should be setting 3 bits, not 2.
So the function you posted (I can't tell if it's yours or the referenced one) called updateBits2
is incorrect.
However, your fix fails when j==31
, and that is something they would bug you about in a coding interview. Instead of (1<<(j+1))-1
, use (1<<j)|((1<<j)-1)
, or shorten the whole line to left = -2<<j;
I came across the same issue. I think the solution was wrong.
int left = max - ((1 << j) - 1);
should be changed to:
int left = max - ((1 << j + 1) - 1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.