Skip to content

Commit 569c882

Browse files
committed
lowbit
1 parent a24dd9f commit 569c882

File tree

2 files changed

+12
-10
lines changed

2 files changed

+12
-10
lines changed

range-sum-query-mutable/NumArray.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
export function lowbit(x: number) {
2+
return x & -x;
3+
}
14
const add = Symbol();
25
export default class NumArray {
36
#tree: number[];
@@ -12,12 +15,10 @@ export default class NumArray {
1215
[add](index: number, val: number) {
1316
while (index < this.#tree.length) {
1417
this.#tree[index] += val;
15-
index += this.#lowBit(index);
18+
index += lowbit(index);
1619
}
1720
}
18-
#lowBit(x: number) {
19-
return x & -x;
20-
}
21+
2122
update(index: number, val: number): void {
2223
this[add](index + 1, val - this.#nums[index]);
2324
this.#nums[index] = val;
@@ -30,7 +31,7 @@ export default class NumArray {
3031
let sum = 0;
3132
while (index > 0) {
3233
sum += this.#tree[index];
33-
index -= this.#lowBit(index);
34+
index -= lowbit(index);
3435
}
3536
return sum;
3637
}

rank-from-stream-lcci/BinaryIndexTree.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
export class BinaryIndexTree<T = number> {
22
defaultValue: T;
33
operation: (existing: T, applied: T) => T;
4-
static lowbit(x: number) {
5-
return x & -x;
6-
}
4+
75
#tree: T[];
86
constructor(
97
public size: number,
@@ -23,15 +21,18 @@ export class BinaryIndexTree<T = number> {
2321
this.defaultValue = defaultValue;
2422
}
2523
update(i: number, value: T) {
26-
for (let p = i; p <= this.size; p += BinaryIndexTree.lowbit(p)) {
24+
for (let p = i; p <= this.size; p += lowbit(p)) {
2725
this.#tree[p] = this.operation(this.#tree[p], value);
2826
}
2927
}
3028
query(n: number) {
3129
let ans = this.defaultValue;
32-
for (let p = n; p > 0; p -= BinaryIndexTree.lowbit(p)) {
30+
for (let p = n; p > 0; p -= lowbit(p)) {
3331
ans = this.operation(ans, this.#tree[p]);
3432
}
3533
return ans;
3634
}
3735
}
36+
export function lowbit(x: number) {
37+
return x & -x;
38+
}

0 commit comments

Comments
 (0)