DIGITAL GURU
Java DSA Portfolio

Count Set Bits, Power of Two & Single Number

Learn Brian Kernighan's Algorithm for set bits, Power of Two check n & (n-1) == 0, and Single Number using XOR.

Anuj Kumar Singh Written by Anuj Kumar Singh (Lead Engineer, 13+ yrs exp) 5 min read Verified Spring Boot 3+ Guide

Real-World Analogy

XOR Single Number trick is like a dance party where everyone has a twin partner—when twin pairs dance together ($X \text{ ^ } X = 0$), they cancel out, leaving ONLY the single unmatched person standing!

Classic Bit Tricks

Power of Two Check: `(n > 0) && ((n & (n - 1)) == 0)`

Production Code Example:

BitTricks.java
public class BitTricks {
    public int singleNumber(int[] nums) {
        int res = 0;
        for (int x : nums) res ^= x; // Duplicate pairs cancel out!
        return res;
    }
    public int countSetBits(int n) {
        int count = 0;
        while (n > 0) { n &= (n - 1); count++; }
        return count;
    }
}

Key Complexity & Algorithmic Takeaways:

When implementing Count Set Bits, Power of Two & Single Number in coding interviews and production applications, keep these core guidelines in mind:

  • Time Complexity Analysis: Always evaluate best-case, average-case, and worst-case time complexities ($O(1)$, $O(\log n)$, $O(n)$, $O(n \log n)$, $O(n^2)$).
  • Space Complexity & Memory Bounds: Account for auxiliary memory usage, call stack frame recursion overhead, and heap allocations.
  • Edge Cases & Validation: Test empty inputs, null pointers, single-element collections, duplicate values, and integer overflow bounds.
  • Optimal vs Naive Solutions: Start with a clear brute-force solution, then optimize using techniques like Hashing, Two Pointers, Windowing, or Dynamic Programming.

Summary Takeaway:

Mastering Count Set Bits, Power of Two & Single Number provides the foundational problem-solving skills needed to pass technical coding interviews at top tech companies and write ultra-performant software systems.

XOR Properties

Key identities: $X \text{ ^ } X = 0$ and $X \text{ ^ } 0 = X$. Order of operations does not matter (Commutative & Associative).