题目链接: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;
}