HDU1390_Binary Numbers【水题】【位运算】

来源:互联网 发布:中国战争潜力知乎 编辑:程序博客网 时间:2024/04/29 12:49
Binary Numbers


Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 2828    Accepted Submission(s): 1755

Problem Description
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.
 
Input
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.
 
Output
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.
 
Sample Input
1
13
 
Sample Output
0 2 3
 
Source

Central Europe 2001, Practice


题目大意:给你一个数N,输出N的二进制形式上为1的数位(从右至左)

思路:每次(N&1)判断末尾是否为1,为1则存入数组ans[]中,不为1则

不存,之后数位自增,N向右移一位,继续判断末尾……


#include<stdio.h>#include<string.h>int ans[110];int main(){    int N,T;    scanf("%d",&T);    while(T--)    {        memset(ans,0,sizeof(ans));        scanf("%d",&N);        int num = 0,count = 0;        while(N)        {            if(N&1)            {                ans[num++] = count;                count++;            }            else            {                count++;            }            N >>= 1;        }        for(int i = 0; i < num; i++)        {            if(i!=num-1)                printf("%d ",ans[i]);            else                printf("%d\n",ans[i]);        }    }    return 0;}



0 0