二进制中1的个数

题目描述

输入一个int型的正整数,计算出该int型数据在内存中存储时1的个数。

输入描述:

write description here:输入一个整数(int类型)

输出描述:

write description here:这个数转换成2进制后,输出1的个数

输入例子:

5

输出例子:

2

调试通过的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//write code here
#include<iostream>
using namespace std;
int number(int num)
{
int count=0;
while(num)
{
++count;
num=(num-1)&num;
}
return count;
}
int main()
{
int num=0;
cin>>num;
cout<<number(num) <<endl;
return 0;
}

来源:牛客网

文章目录
  1. 1. 题目描述
    1. 1.1. 输入描述:
    2. 1.2. 输出描述:
    3. 1.3. 输入例子:
    4. 1.4. 输出例子:
  2. 2. 调试通过的代码
|