Dylans loves numbers
Description
Who is Dylans?You can find his ID in UOJ and Codeforces.
His another ID is s1451900 in BestCoder.
And now today’s problems are all about him.
Dylans is given a number
N
.
He wants to find out how many groups of “1” in its Binary representation.
If there are some “0”(at least one)that are between two “1”,
then we call these two “1” are not in a group,otherwise they are in a group.
Input
In the first line there is a number
T is the test number.
In the next
Output
For each test case,output an answer.
Sample Input
1
5
Sample Output
2
题意:给你一个数,然后叫你求这个数以二进制表示时有多少组1,当两个1之间有至少一个0,这两个1是不同的两个组。比如5,其二进制数为101,中间有一个0,所以最终有两组1。
分析:首先可以将所给 的数的二进制存进一个数组,然后判断这个数组有多少组1就行了。
代码:
#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<vector>
#include<math.h>
#include<queue>
#include<algorithm>
using namespace std;
const int inf = 0x3f3f3f3f;
long long n;
int main ()
{
int t;
scanf ("%d",&t);
long long cnt;
int a[70];
while (t--){
cnt=0;
scanf ("%lld",&n);
int k=0;
int temp;
while (n){//将n的二进制数存进a数组
temp=n%2;
a[k++]=temp;
n/=2;
}
if (a[0]==1) cnt++;
for (int i=1;i<k;i++){//判断有多少组1
if (a[i]==1&&a[i]!=a[i-1]){//当当前数为1且前一个数为0,则加1;
cnt++;
}
}
if (n==1||n==2||n==3||n==4)printf ("1\n");
printf ("%lld\n",cnt);
}
return 0;
}