HDOJ(HDU) 2502 月之数(进制)
Problem Description
当寒月还在读大一的时候,他在一本武林秘籍中(据后来考证,估计是计算机基础,狂汗-ing),发现了神奇的二进制数。
如果一个正整数m表示成二进制,它的位数为n(不包含前导0),寒月称它为一个n二进制数。所有的n二进制数中,1的总个数被称为n对应的月之数。
例如,3二进制数总共有4个,分别是4(100)、5(101)、6(110)、7(111),他们中1的个数一共是1+2+2+3=8,所以3对应的月之数就是8。
Input
给你一个整数T,表示输入数据的组数,接下来有T行,每行包含一个正整数 n(1<=n<=20)。
Output
对于每个n ,在一行内输出n对应的月之数。
Sample Input
3
1
2
3
Sample Output
1
3
8
这个题目。。用Java来计算会超时0.0
n位二进制数一共有x=2^(n-1)个数,然后举几个例子就可以看出来了:
例如:
输入4,则一共有如下这么多4位二进制数:
1 0 0 0
1 0 0 1
1 0 1 0
1 0 1 1
1 1 0 0
1 1 0 1
1 1 1 0
1 1 1 1
第一列有x个1,以后每列都有x/2个1,然后一共有s=x+(n-1)*x/2个1
JavaAC:
import java.util.Scanner;
public class Main{ public static void main(String[] args) { Scanner sc= new Scanner(System.in); int t =sc.nextInt(); while(t-->0){ int n =sc.nextInt(); int cont =0; int x = (int)Math.pow(2, n-1); //int x = (int)Math.pow(2, n)-(int)Math.pow(2, n-1);//一样的 cont+=x*(n-1)/2; System.out.println(cont+x); } }
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
C模拟输出:
(这个用Java会超时)
#include <iostream>
#include <stdio.h>
#include<math.h>
using namespace std;
int main()
{ int t ; scanf("%d",&t); while(t-->0){ int n ; int cont =0; int x; scanf("%d",&n); for(int i=pow(2, n-1);i<=pow(2, n)-1;i++){ x=i; while(x>0) { if((x%2)==1) cont++; x/=2; } } printf("%d\n",cont); } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
文章来源: chenhx.blog.csdn.net,作者:谙忆,版权归原作者所有,如需转载,请联系作者。
原文链接:chenhx.blog.csdn.net/article/details/51346843
- 点赞
- 收藏
- 关注作者
评论(0)