Brian Kernighan’s Algorithm 정수의 이진 표현에서 ‘1’의 개수, 즉 ‘set bits’ 의 개수를 효율적으로 세는 데 사용되는 알고리즘이다.
Core Idea
정수 n에 대해 다음을 반복한다:
n = n & (n - 1);count += 1;n & (n-1)은 n의 가장 낮은 위치의1인 bit 하나를0으로 바꿈- 그 결과
n에1인 bit 가k개 있으면 정확히k번만 루프를 돌게 됨
Algorithm 의 시간복잡도는 O(k) (k = num of set bits)로, 매 비트(w)마다 도는 단순 방법(O(w))보다 평균적으로 훨씬 빠르다.
그렇기에 sparse bit representation 에서 특히 유용하다.
Commonly Used
check if power of two
// n > 0bool is_power_of_two(uint32_t n){ return n && ((n & (n - 1)) == 0);}Note (builtin popcount functions for cpp)
단순히 pop count 가 필요하다면, GCC/Clang 에서 제공하는 내장 함수를 사용하는 것이 가장 빠르고 간편하다.
int count = __builtin_popcountll(x); // for long longint count = __builtin_popcount(x); // for intint count = __builtin_popcountl(x); // for longiterate only for set bits
while (n > 0) { n &= n - 1 // use of n // lsb = n & -n; -> get lowest set bit }