본문 바로가기
Algorithms/simulation

Hamming Weight 1

by OKOK 2021. 4. 13.

- int = 0x12345678 일 때. 이 때 비트가 1인 개수 찾기

- O(32) -> O(5) = O(logN) 으로 시간을 줄 일 수 있음.

- 2비트 끼리, 4비트 끼리, 8비트 끼리, 16비트 끼리, 32비트 단위로 계산을 하여 1의 갯수를 구할 수 있음

#include <stdio.h>
const int m1  = 0x55555555; 
const int m2  = 0x33333333; 
const int m4  = 0x0f0f0f0f; 
const int m8  = 0x00ff00ff; 
const int m16 = 0x0000ffff; 
const int h01 = 0x01010101; 

int popcount_a(int x)
{
	x = (x & m1 ) + ((x >>  1) & m1 ); 
	x = (x & m2 ) + ((x >>  2) & m2 ); 
	x = (x & m4 ) + ((x >>  4) & m4 ); 
	x = (x & m8 ) + ((x >>  8) & m8 ); 
	x = (x & m16) + ((x >> 16) & m16); 
	return x;
}


int main()
{
	int bitmap = 0x12345678;
	int count;

	count = popcount_a(bitmap);
	printf("count=%d\n", count );
	return 0;
}

'Algorithms > simulation' 카테고리의 다른 글

Hamming Weight 3  (0) 2021.04.13
Hamming Weight 2  (0) 2021.04.13
find first set / find next bit  (0) 2021.04.13
테트리스  (0) 2020.01.10
테트리스  (0) 2020.01.10

댓글