前几天做笔试碰到这样一个题,当时没有想出来,相当遗憾。
这个函数的功能是X转换为二进制数中1的个数。
#include <stdio.h> int fun(int num) { int count = 0; while(num) { num &= (num-1); ++count; } return count; } int main() { printf("%d\n",fun(13)); printf("%d\n",fun(011111)); printf("%d\n",fun(01011011)); return 0; } ~
1@ubuntu:~/demo$ ./a.out
3
5
5