首页 > 代码库 > HDU1390_Binary Numbers【水题】【位运算】
HDU1390_Binary Numbers【水题】【位运算】
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; }
HDU1390_Binary Numbers【水题】【位运算】
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。