【剑指offer-解题系列(10)】二进制中1的个数

来源:互联网 发布:淘宝用工具吧怎样打折 编辑:程序博客网 时间:2024/06/14 18:31


题目描述

输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
分析
对于32位int型,只需要逐步位移,然后与上0x01就行了;
代码实现
int  NumberOf1(int n) {    int count = 0;    for(int i=0;i<32;i++){        if(n&0x01){            count++;        }        n=n>>1;    }    return count;}