File tree Expand file tree Collapse file tree 1 file changed +3
-3
lines changed Expand file tree Collapse file tree 1 file changed +3
-3
lines changed Original file line number Diff line number Diff line change 12
12
public class CountSetBits {
13
13
14
14
/**
15
- * Unoptimized version.
15
+ * Unoptimized version. Works for -ve numbers as well.
16
16
*
17
17
* @param number
18
18
* @return
@@ -29,7 +29,7 @@ static int countSetBits(int number) {
29
29
}
30
30
31
31
/**
32
- * Optimized version.
32
+ * Optimized version. Works for -ve numbers as well.
33
33
*
34
34
* Uses BRIAN KERNIGAN'S bit counting. Acc. to this, the right most/least significant set bit is unset
35
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
42
*/
43
43
static int countSetBits (long n ) {
44
44
int count = 0 ;
45
- while (n > 0 ) {
45
+ while (n != 0 ) {
46
46
n &= n - 1 ; // right most set bit in n is unset
47
47
count ++;
48
48
}
You can’t perform that action at this time.
0 commit comments