One Piece 题解

One Piece

链接:https://ac.nowcoder.com/acm/contest/908/C
来源:牛客网

题目描述

Luffy once saw a particularly delicious food, but he didn’t have the money, so he asked Nami for money. But we all know that Nami can’t easily give money to Luffy. Therefore, Nami decided to take a test of Luffy. If Luffy was right, Nami would give him money, otherwise Luffy would only be hungry. The problem is as follows: Give you an 32-bit integer n and find the number of 1 in the binary representation of the integer.
You are the most trusted friend of Luffy, and he is now asking for help.

输入描述:

There are multiple test cases. The first line of the input contains an integer T(T<=10), indicating the number of test cases. For each test case:

The first line contains an 32-bit integer n(-1e9 <= n <= 1e9)

输出描述:

For each test case output one line containing one integer, indicating the number of 1 in the binary representation of the integer.

示例1

输入
3
1
2
3
输出
1
1
2

说明

The binary of 1 is 01, so the number of 1 is 1, and the binary of 2 is 10, so the number of 1 is 1,The binary of 3 is 11, so the number of 1 is 2.

示例2

输入
1
-1
输出
32

说明

The binary of -1 is 11111111111111111111111111111111, so the number of 1 is 32.

题目分析

题目要求我们计算一个数的二进制里1的个数,我们很容易想到位运算中的lowbit,lowbit运算是找到当前二进制中最后面的一个一,所以我们只需不断的减去lowbit,直到原数对于零,就可以得到当前数二进制中一的个数。
lowbit运算 lowbit(n)=n&-n;

#include<iostream>
#include<algorithm>

using namespace std;

int main()
{
	int T;
	cin >> T;
	while (T--)
	{
		int n,ans=0;
		cin >> n;
		for(int i = n; n; n -= n & -n)
			ans++;
		cout << ans << endl;
	}


	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值