-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathjs-util-bits.js
65 lines (51 loc) · 1.42 KB
/
js-util-bits.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class BitManip {
constructor(n) {
this.n = n;
}
getNum() {
return this.n;
}
getBitCount() {
let sum = 0;
while (this.n) {
sum += this.n & 1;
this.n = this.n >> 1;
}
return sum;
}
getKthIndexBit(k) {
if (k < 0) {
console.log("k -ve invalid - getKthIndexBit");
return this.n;
}
return (this.n >> k) & 1;
// return this.n & (1 << k); // ---- bitwise AND (&)
}
setKthIndexBit(k) {
if (k < 0) {
console.log("k -ve invalid - setKthIndexBit");
return this.n;
}
this.n = this.n | (1 << k); // ---- bitwise OR (|)
return this.n;
}
unsetKthIndexBit(k) {
if (k < 0) {
console.log("k -ve invalid - unsetKthIndexBit");
return this.n;
}
// & this.n, with a number with all set bits except the k'th bit
this.n = this.n & ~(1 << k); // ---- bitwise AND (&)
return this.n;
}
// ----------
/*
toggleKthBit(k) {
if (k < 1) return this.n;
// ^ this.n, with a number with all set bits except the k'th bit
return this.n ^ (1 << k); // ---------------- bitwise AND (&)
}
*/
}
// let o1 = new BitManip(682);
// let act = o1.setKthIndexBit(0); // 683