Skip to content

Commit c3c8d02

Browse files
authored
Update Counting Bits.js
When i === pow, pow doubles; For next iteration, i is smaller than pow. That will be the issue if i is less than pow for ELSE condition. So added another variable copyOfPow (old pow) to manage the scenario when copyOfPow < i < pow.
1 parent 3c7ac05 commit c3c8d02

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

Counting Bits.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,18 @@
1818
var countBits = function(num) {
1919
var result = [],
2020
pow = 1,
21+
copyOfPow = 1,
2122
i;
2223

2324
result[0] = 0;
2425

25-
for (i = 1; i < num; i++) {
26+
for (i = 1; i <= num; i++) {
2627
if (i === pow) {
2728
result[i] = 1;
29+
copyOfPow = pow;
2830
pow *= 2;
2931
} else {
30-
result[i] = result[pow] + result[i - pow];
32+
result[i] = result[copyOfPow] + result[i - copyOfPow];
3133
}
3234
}
3335

0 commit comments

Comments
 (0)