EXAMPLE:
Input: N = 10000000000, M = 10101, i = 2, j = 6
Output: N = 10001010100
This code operates by clearing all bits in N between position i and j, and then ORing to put
M in there.
1 public static int updateBits(int n, int m, int i, int j) {
2 int max = ~0; /* All 1’s */
3
4 // 1’s through position j, then 0’s
5 int left = max - ((1 << j) - 1);
6
7 // 1’s after position i
8 int right = ((1 << i) - 1);
9
10 // 1’s, with 0s between i and j
11 int mask = left | right;
12
13 // Clear i through j, then put m in there
14 return (n & mask) | (m << i);
15 }
Input: N = 10000000000, M = 10101, i = 2, j = 6
Output: N = 10001010100
This code operates by clearing all bits in N between position i and j, and then ORing to put
M in there.
1 public static int updateBits(int n, int m, int i, int j) {
2 int max = ~0; /* All 1’s */
3
4 // 1’s through position j, then 0’s
5 int left = max - ((1 << j) - 1);
6
7 // 1’s after position i
8 int right = ((1 << i) - 1);
9
10 // 1’s, with 0s between i and j
11 int mask = left | right;
12
13 // Clear i through j, then put m in there
14 return (n & mask) | (m << i);
15 }
No comments:
Post a Comment