ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Count Set Bits

Java

Goal -- WPM

Ready
Exercise Algorithm Area
1public class BitCounter {
2
3/**
4* Counts the number of set bits (1s) in the binary representation of an integer.
5* Handles non-negative integers.
6*
7* @param n The integer to count bits for.
8* @return The number of set bits.
9*/
10public int countSetBits(int n) {
11if (n < 0) {
12// For simplicity, we'll return 0 for negative numbers.
13// In a real scenario, you might handle two's complement.
14return 0;
15}
16if (n == 0) {
17return 0;
18}
19
20int count = 0;
21while (n > 0) {
22n &= (n - 1); // Brian Kernighan's algorithm
23count++;
24}
25return count;
26}
27
28public static void main(String[] args) {
29BitCounter bc = new BitCounter();
30System.out.println("Bits in 10 (1010): " + bc.countSetBits(10)); // Expected: 2
31System.out.println("Bits in 7 (0111): " + bc.countSetBits(7)); // Expected: 3
32System.out.println("Bits in 0: " + bc.countSetBits(0)); // Expected: 0
33}
34}
Algorithm description viewbox

Count Set Bits

Algorithm description:

This Java method efficiently counts the number of set bits (1s) in the binary representation of a non-negative integer. It utilizes Brian Kernighan's algorithm, which repeatedly flips the least significant set bit to zero until the number becomes zero. This technique is often used in bit manipulation tasks, performance-critical code, and low-level programming.

Algorithm explanation:

The `countSetBits` method uses Brian Kernighan's algorithm. The core operation `n &= (n - 1)` clears the least significant set bit. For example, if `n = 12` (binary `1100`), `n - 1 = 11` (binary `1011`). `n & (n - 1)` results in `1000` (decimal 8). This process is repeated until `n` becomes 0. The loop iterates exactly as many times as there are set bits. The time complexity is O(k), where k is the number of set bits, which is at most O(log n) or O(32) for a 32-bit integer. Space complexity is O(1) as it uses a constant amount of extra space.

Pseudocode:

function countSetBits(n):
  if n is negative:
    return 0
  if n is 0:
    return 0

  count = 0
  while n > 0:
    n = n AND (n - 1) // Clear the least significant set bit
    count = count + 1
  return count