题解 | #求int型正整数在内存中存储时1的个数#

求int型正整数在内存中存储时1的个数

http://www.nowcoder.com/practice/440f16e490a0404786865e99c6ad91c9

(1)辗转相除法:
#include <stdio.h>
int main(){
    int a,count = 0;
    scanf("%d",&a);
    while(a){
        if(a % 2 == 1){  //辗转相除法
            count++;
        }
        a /= 2;
    }
    printf("%d\n",count);
    return 0;
}

(2)移位运算:
#include <stdio.h>
int main(){
    int a,count = 0;
    scanf("%d",&a);
    while(a){
        count += a & 1;      //与运算,同 1 为 1
        a = a >> 1;          //与运算一次后,右移一位,将与过的最低位舍弃
    }
    printf("%d\n",count);
    return 0;
}

全部评论

相关推荐

06-26 17:24
已编辑
宁波大学 Java
迷失西雅图:别给,纯kpi,别问我为什么知道
点赞 评论 收藏
分享
评论
7
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务