LintCode 题目:判断一个整数中有多少个1

URL:https://www.lintcode.com/problem/number-of-1-bits/description

描述

写一个函数,其以无符号整数为输入,而输出对应二进制数所具有的“1”的位数(也被称为汉明权重)

样例

样例 1

输入:n = 11
输出:3
解析:11(10) = 1011(2), 返回 3

样例 2

输入:n = 7
输出:3
解析:7(10) = 111(2), 返回 3

在代码段中添加:

int count=0;
        while(n!=0){
            if(n%2==1)
                count++;
            n=n/2;
        }
        if(n==1)
            count++;
        return count;

 

 

即可:

发布了303 篇原创文章 · 获赞 550 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_42410605/article/details/103280915
今日推荐