您的位置:首页 > 其它

位运算---水题

2015-06-20 22:15 423 查看
http://bestcoder.hdu.edu.cn/contests/contest_chineseproblem.php?cid=604&pid=1001

问题描述
给定一个数 N 把统计它的二进制表示里, 1的块数。 如  5 = 101 有两块 1 。 如 11 = 1011 也是有两块 1

输入描述
第一行输入一个T, 表示有T组数据。 然后有T行, 每行一个整数(N)。

输出描述
对于每组数据,输出一个数表示答案。

输入样例
1
5

输出样例
2


#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
int T;
long long x;
scanf("%d",&T);
for (;T--;)
{
scanf("%I64d",&x);
int sum=0;
for (;x;x>>=1)
if (x&1)
{
sum++;
while (x&1) x>>=1;
}
printf("%d\n",sum);
}
}


View Code

用位运算交换两个数的值(是不是很炫酷?)

#include <iostream>
using namespace std;

void inplace_swap(int *x, int *y)
{
*y = *x ^ *y;  // Step 1
*x = *x ^ *y;  // Step 2
*y = *x ^ *y;  // Step 3
}

int main()
{
int a = 13, b = 14;
int * m = &a, *n = &b;
cout<< *m << '\t' << *n << endl << endl;
inplace_swap(m, n);
cout<< *m << '\t' << *n << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: