洛谷:P7071
OJ: P4966
方法一:
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 32 33 34 35 | /**************************************************************** * Description: 2020年CSP_J普及组初赛第一题,优秀的拆分 * Author: Alex Li * Date: 2022-10-15 20:32:49 * LastEditTime: 2023-10-20 10:33:49 ****************************************************************/ #include<iostream> using namespace std; int n,now=1; int main(){ cin>>n; if (n%2!=0){ printf("-1"); return 0; } //如果n为奇数,直接输出-1。 while(now<=n){ now*=2; } now/=2; do{ if(n>=now){ cout<<now<<' '; n=n-now; } now/=2; if(now>n){ now/=2; } }while(now>1); return 0; } |
方法二:用数组存
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 32 33 34 35 36 | /**************************************************************** * Description: 2020普及组复赛第一题:优秀的拆分 ,解法二 * Author: Alex Li * Date: 2023-10-20 11:03:15 * LastEditTime: 2023-10-20 11:04:36 ****************************************************************/ #include<iostream> #include <cmath> using namespace std; int n; int a[110]; int len; int main(){ cin>>n; if (n%2!=0){ cout<<-1; return 0; } //如果n为奇数,直接输出-1。 while(n){ a[len++]=n%2; n/=2; } for (int i = len; i >=0; i--) { if(a[i]){ int x=pow(2,i); cout<<x<<" "; } } return 0; } |