quickBitcount (quickBitcount)

quickBitcount (quickBitcount)

quickBitcount 教學與筆記。

說明

x &= (x-1) 的功能是消除右向左遇到的第一個1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>

unsigned quickBitcount(unsigned x) {
int count = 0;

while(x) {
x &= (x-1);
count++;
}
return count;
}

void main() {
printf("%d\n", quickBitcount(78)); // 4
}
Author

Meow Lucian

Posted on

2022-04-13

Updated on

2022-07-08

Licensed under

Comments