【腾讯面试题目】非循环方式 计算一个32位整数中被置1的位数

这是一个填空题:

#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;

int get_bit_count_1(int num){
    if(num==0){
        return 0;
    }else{
        return 【    】;
    }
}


int get_bit_count_2(int num){
    //         0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
    int dic[]={0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4};
    return  dic[(num&0x000f   )>>0 ]   +dic[(num&0x00f0    )>>4 ] +
            dic[(num&0x0f00   )>>8 ]   +dic[(num&0xf000    )>>12] +
            dic[(num&0xf0000  )>>16]   +dic[(num&0xf00000  )>>20] +
            dic[(num&0xf000000)>>24]   +dic[(num&0xf0000000)>>28];
}


int main(){
    for(int num=0;num<100;num++){
        cout<<"["<<num<<"]"<<get_bit_count_1(num)<<endl;
    }
    /*
    for(int num=0;num<100;num++){
        cout<<"["<<num<<"]"<<get_bit_count_2(num)<<endl;
    }
    */
    return 0;
}

第二个空 是 dic[]中间的内容,共8个,不过被我神奇的填出来了。第一个空 还是不知道中。怎么一句话就搞定,不可以直接调用 get_bit_count_2,因为 get_bit_count_1前没有这个函数的声明。

原文地址:https://www.cnblogs.com/ayanmw/p/3494050.html