面试题目写一个int Fun(byte); (0x99即10011001返回其中1的个数4)

来源:互联网 发布:dnf账号数据异常 编辑:程序博客网 时间:2024/06/06 10:25
/*int Fun(byte);  (0x99即10011001返回其中1的个数4)*/#include<stdio.h>typedef unsigned char byte;int Fun(byte);int main(int argc , char *argv[]){printf("num of 1 : %d\n",Fun(255));return 0;}int Fun(byte bt){byte val = 1;int cnt = 0;while(val != 0)   //到达临界点128后,val*=2等于0 (溢出byte范围0~255){if((bt & val) != 0)++cnt;val *= 2;}return cnt;}