Skip to content

Commit e88a8ae

Browse files
author
Ram swaroop
committed
count set bits for -ve nos: done
1 parent f280044 commit e88a8ae

File tree

1 file changed

+3
-3
lines changed

1 file changed

+3
-3
lines changed

src/me/ramswaroop/bits/CountSetBits.java

+3-3
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
public class CountSetBits {
1313

1414
/**
15-
* Unoptimized version.
15+
* Unoptimized version. Works for -ve numbers as well.
1616
*
1717
* @param number
1818
* @return
@@ -29,7 +29,7 @@ static int countSetBits(int number) {
2929
}
3030

3131
/**
32-
* Optimized version.
32+
* Optimized version. Works for -ve numbers as well.
3333
*
3434
* Uses BRIAN KERNIGAN'S bit counting. Acc. to this, the right most/least significant set bit is unset
3535
* in each iteration. The time complexity is proportional to the number of bits set.
@@ -42,7 +42,7 @@ static int countSetBits(int number) {
4242
*/
4343
static int countSetBits(long n) {
4444
int count = 0;
45-
while (n > 0) {
45+
while (n != 0) {
4646
n &= n - 1; // right most set bit in n is unset
4747
count++;
4848
}

0 commit comments

Comments
 (0)