HDU 2502 月之数 (数学 || bitset妙用)

来源:互联网 发布:数据库基础知识视频 编辑:程序博客网 时间:2024/05/17 03:31

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

这题本属数学题,然而数学渣渣,发现bitset很好搞定。最后也顺带附上数学解法。就当学习了~

##include <iostream>#include <bitset>using namespace std;//bitsetint main() {    int t, n;    scanf("%d", &t);    while (t--) {        scanf("%d", &n);        int sum = 0;        for (int i = 1 << n - 1, endn = 1 << n; i < endn; ++i) {            bitset<21> bs(i);            sum += bs.count();        }        printf("%d\n", sum);    }    return 0;}//法二:数学方法#include <iostream>#include <cmath>using namespace std;int main() {    int t, n;    scanf("%d", &t);    while (t--) {        scanf("%d", &n);        printf("%d\n", (int)(pow(2, n - 2) * (n + 1)));    }    return 0;}
0 0
原创粉丝点击