Skip to content

Commit 8d784b9

Browse files
authored
CountSetBits code file added
1 parent 47a9b1b commit 8d784b9

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// CountSetBits.java
2+
package com.thealgorithms.bitmanipulation;
3+
4+
public final class CountSetBits {
5+
private CountSetBits() {
6+
}
7+
8+
/**
9+
* CountSetBits class provides a method to count the number of set bits (1s) in an integer.
10+
* Implementation by Pankaj Kumar Bind (https://github.com/Pankaj-Bind).
11+
*/
12+
public static int countSetBits(int n) {
13+
int count = 0;
14+
while (n > 0) {
15+
count += n & 1;
16+
n >>= 1;
17+
}
18+
return count;
19+
}
20+
}
21+
22+
/* Time Complexity: O(log n)
23+
* Space Complexity: O(1)
24+
*/

0 commit comments

Comments
 (0)