Intermediate·Concept·2 min read

Bit manipulation in Java

Practice this question

Common operations

  • &, |, ^, ~, <<, >>
  • check even/odd
  • count set bits
  • single number
  • power of two

Example: count set bits

java
int countSetBits(int n) {
    int count = 0;
    while (n > 0) {
        n &= (n - 1);
        count++;
    }
    return count;
}

Adapted from 15_DSA_JAVA.md · “12. Bit manipulation in Java”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.