Skip to content

Commit 1606b02

Browse files
fix(5.1):use bit mask and bit operators (careercup#80)
1 parent e7b402e commit 1606b02

File tree

1 file changed

+8
-11
lines changed

1 file changed

+8
-11
lines changed
Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,11 @@
1-
var insertion = function(N, M, i, j) {
2-
var n = N.split('');
3-
var m = M.split('');
4-
var nlength = n.length - 1;
5-
var mlength = m.length - 1;
6-
for (var a = 0; a < j - i + 1; a++) {
7-
console.log(m[mlength - a]);
8-
n[nlength - (i + a)] = m[mlength - a];
9-
}
10-
return n.join('');
1+
const insertion = (N, M, i, j) => {
2+
const bitMask = (-1 << (j + 1)) | ((1 << i) - 1);
3+
const clearedN = N & bitMask;
4+
const shiftedM = M << i;
5+
return clearedN | shiftedM;
116
};
127

138
/* TEST */
14-
console.log(insertion('10000000000', '10011', 2, 6), '10001001100');
9+
const N = parseInt(10000000000, 2);
10+
const M = parseInt(10011, 2);
11+
console.log(insertion(M, N, 2, 6).toString(2), 10001001100);

0 commit comments

Comments
 (0)