CSU1732-XueXX and Binary-简单模拟

本文介绍了一个简单的程序设计问题:对于给定的十进制整数,如何计算其二进制表示中1的个数。通过使用位操作,文章提供了一种有效的方法来解决这个问题,并附带了完整的C++代码实现。

L: XueXX and Binary

Description

XueXX is a clever boy. And he always likes numbers in binary(二进制). What an interesting hobby!

Now XueXX has some number in decimal(十进制), he wants to know how many “1”s in a number if the number is written in binary.

Input

The first line of input contains the number of test cases T (T<=100). The descriptions of the test cases follow: The first line of each test case contains one integer a (0

Output

For each test case, output a single line containing the result.

Sample Input

3
1
91
735

Sample Output

1
5
8

这个题目就是输入一个int范围内的数,需要你输出将它转成二进制以后有多少个1
这个题蛮水的,拿出来说一下主要是因为求解过程中那个循环以后还会用到很多次相似的形式,比如快速幂

#include <bits/stdc++.h>
#define N 10100
#define INF 0x3f3f3f3f
#define LL long long
#define mem(a,n) memset(a,n,sizeof(a))
#define fread freopen("in.txt","r",stdin)
#define fwrite freopen("out.txt","w",stdout)
using namespace std;
int main()
{
    ios::sync_with_stdio(false);
    int n,f,cnt;
    cin>>n;
    while(n--){
        cin>>f;
        cnt=0;
        while(f){//注意这个循环,以后还会看到长得蛮像的循环
            if(f&1){
                ++cnt;
            }
            f>>=1;
        }
        cout<<cnt<<endl;
    }
    return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值