2013
12-09

# Binary Numbers

Given a positive integer n, find the positions of all 1′s in its binary representation. The position of the least significant bit is 0.

Example

The positions of 1′s in the binary representation of 13 are 0, 2, 3.

Task

Write a program which for each data set:

reads a positive integer n,

computes the positions of 1′s in the binary representation of n,

writes the result.

The first line of the input contains exactly one positive integer d equal to the number of data sets, 1 <= d <= 10. The data sets follow.

Each data set consists of exactly one line containing exactly one integer n, 1 <= n <= 10^6.

The output should consists of exactly d lines, one line for each data set.

Line i, 1 <= i <= d, should contain increasing sequence of integers separated by single spaces – the positions of 1′s in the binary representation of the i-th input number.

1
13

0 2 3

#include <iostream>
using namespace std;
int main()
{
int d, n, i, a[32], l, flag;
cin >> d;
while (d--)
{
cin >> n;
l = 0;
while (n)
{
a[l++] = n%2;
n /= 2;
}
flag = 1;
for (i = 0; i < l; i++)
{
if(a[i])
if (flag)
{
cout << i;
flag = 0;
}
else
cout << " " << i;
}
cout<<endl;
}
return 0;
}

1. #include <cstdio>
#include <cstring>

const int MAXSIZE=256;
//char store[MAXSIZE];
char str1[MAXSIZE];
/*
void init(char *store) {
int i;
store['A']=’V', store['B']=’W',store['C']=’X',store['D']=’Y',store['E']=’Z';
for(i=’F';i<=’Z';++i) store =i-5;
}
*/
int main() {
//freopen("input.txt","r",stdin);
//init(store);
char *p;
while(fgets(str1,MAXSIZE,stdin) && strcmp(str1,"STARTn")==0) {
if(p=fgets(str1,MAXSIZE,stdin)) {
for(;*p;++p) {
//*p=store[*p]
if(*p<’A’ || *p>’Z') continue;
if(*p>’E') *p=*p-5;
else *p=*p+21;
}
printf("%s",str1);
}
fgets(str1,MAXSIZE,stdin);
}
return 0;
}