【C语言做题系列】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.
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
题意:
输入一个数,然后将它转换成二级制数,再找出其中为“1”的位置,并输出。

注意:
本题的输出格式有讲究。每两个输出之间才能有一个空格,不能有多余的空格。

算法思维:
转换成二进制数后,通过数组存储,将数组遍历一遍,其中等于1的便输出。

上代码:

#include <stdio.h>
#include <string.h>
const int maxn=1e5+5;
int a[maxn];
int k = 0;              //注意我这里定义的是全局变量k,可以在全局中使用
int change(int n)      //此为转换二进制数的函数,不懂得同学可以多总结总结
{
    int r;
    while(n)
    {
        a[k++]=n%2;
        n/=2;
    }
}
int main()
{
    int d;
    int n;
    int len;
    scanf("%d", &d);
    while(d--)
    {
        scanf("%d", &n);
        change(n);
        int flag =1;
        for(int i=0; i<k; i++)      //k为全局变量,所以此处的k经过函数处理可以使用。
        {

            if(a[i]==1)
            {
                if(flag==1)        //前面定义了标志变量flag,用来判断是否是第一个数,题目要求每两个结果之间才能有一个空格。
                {
                    printf("%d", i);
                    flag=0;
                }
                else
                    printf(" %d", i);
            }
        }
        k=0;                           //此处需要重置k的值,方便下一轮循环的运行,否则会出错。
        printf("\n");
    }
    return 0;
}

心得:
题做得多了就有感触了,不需要记住过去的代码,只需要有感觉,你就能写得出。

发布了16 篇原创文章 · 获赞 0 · 访问量 448

猜你喜欢

转载自blog.csdn.net/qq_45627679/article/details/104293125