您的位置:首页 > 编程语言 > C语言/C++

【HDU】1390 Binary Numbers

2018-04-01 11:52 337 查看
[align=left]Problem Description[/align]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.
 [align=left]Input[/align]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.
 [align=left]Output[/align]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.
 [align=left]Sample Input[/align]
1
13[align=left]Sample Output[/align]
0 2 3

这道题两遍AC,第一次因为格式的问题,最后一个数字后面应该没有空格
代码:#include <stdio.h>
#include <string>
int main() {
int N,n,num;
int s[100];
scanf("%d",&N);
while (N--) {
int i=0;
num=0;
scanf("%d",&n);
while (n) {
s[i]=n%2;
n/=2;
i++;
}
for (int k=0; k<i; k++) {
if (s[k]==1) {
num++;
if(num==1)
printf("%d",k);
else
printf(" %d",k);
}
}
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C语言