C程序设计语言 Exercise 2-9

来源:互联网 发布:软件开发团队建设 编辑:程序博客网 时间:2024/04/27 03:04

Exercise 2-9. In a two's complement number system, x &= (x-1) deletes the rightmost 1-bit
in x. Explain why. Use this observation to write a faster version of bitcount.

#include "stdio.h"int BitCount(unsigned int x);int main(){int num = 9;printf("%d,%d",BitCount(num),num);}int BitCount(unsigned int x){int count = 0;while(x != 0){x &= (x - 1);/* * (x - 1)每次都会将x最右端为1的bit位变为0 */count++;}return count;}


原创粉丝点击