We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent f280044 commit e88a8aeCopy full SHA for e88a8ae
src/me/ramswaroop/bits/CountSetBits.java
@@ -12,7 +12,7 @@
12
public class CountSetBits {
13
14
/**
15
- * Unoptimized version.
+ * Unoptimized version. Works for -ve numbers as well.
16
*
17
* @param number
18
* @return
@@ -29,7 +29,7 @@ static int countSetBits(int number) {
29
}
30
31
32
- * Optimized version.
+ * Optimized version. Works for -ve numbers as well.
33
34
* Uses BRIAN KERNIGAN'S bit counting. Acc. to this, the right most/least significant set bit is unset
35
* in each iteration. The time complexity is proportional to the number of bits set.
@@ -42,7 +42,7 @@ static int countSetBits(int number) {
42
*/
43
static int countSetBits(long n) {
44
int count = 0;
45
- while (n > 0) {
+ while (n != 0) {
46
n &= n - 1; // right most set bit in n is unset
47
count++;
48
0 commit comments