哈理工OJ 1971 Power of Two(拆分整数为2的次幂的和)

题目链接:http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=1971

Power of Two
Time Limit: 2000 MS Memory Limit: 65536 K
Total Submit: 197(83 users) Total Accepted: 92(77 users) Rating: Special Judge: No
Description
You have been given a number, you should decomposite it into sum of power of two in descending order. For example:

240 = 128 + 64 + 32 + 16

and

115 = 64 + 32 + 16 + 2 + 1

Input
The first line contains an integer T(T ≤ 50), indicating the number of test cases. Each test case contains one number n(1 ≤ n ≤ 2^31-1) the number we are going to decomposite.

Output
For each test case, output “Case #i: ” followed by one line the conresponding result.

Sample Input
2
240
115

Sample Output
Case #1: 240 = 128 + 64 + 32 + 16
Case #2: 115 = 64 + 32 + 16 + 2 + 1

Source
“科林明伦杯”哈尔滨理工大学第三届ACM程序设计团队赛
Author
xiaodao

【思路分析】先把2的次幂都求出来,然后直接扫一遍就OK了。
【AC代码】

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<stack>
#include<queue>
using namespace std;
#define ll long long

ll a[33];

void init()
{
    for(ll i=0;i<=32;i++)
    {
        a[i]=(ll)pow(2,i);
    }
}

ll re[35];

int main()
{
    init();
    int t,iCase=0;
    scanf("%d",&t);
    while(t--)
    {
        ll n,cnt=0;
        scanf("%lld",&n);
        ll x=n;
        for(ll i=32;i>=0;i--)
        {
            if(n>=a[i])
            {
                n-=a[i];
                re[cnt++]=a[i];
            }
        }
        printf("Case #%d: %lld = %lld",++iCase,x,re[0]);
        for(ll i=1;i<cnt;i++)
        {
            printf(" + %lld",re[i]);
        }
        printf("\n");
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值