30分求助

P7071 [CSP-J2020] 优秀的拆分

这题是位运算,如果n%2==1,那么不合法,每次记录n&-n的结果,倒序输出。 ```cpp #include<bits/stdc++.h> using namespace std; const int MAXN = 1e5 + 10; int n,ans[MAXN],tot; int main(){ cin >> n; if (n & 1 != 0){ cout << -1; return 0; } while (n){ ans[++tot] = n & -n; n -= n & -n; } for (int i = tot; i >= 1; i--){ cout << ans[i] << ' '; } return 0; } ```
by heyx0201 @ 2023-09-13 20:10:56


```cpp #include<bits/stdc++.h> #define int long long using namespace std; int n; int a[30]; signed main() { cin>>n; if(n&1)//位运算判奇偶 { cout<<"-1";//如果是奇数直接排除 return 0; } a[1]=1; for(int i=2;i<=26;i++)//从2的2次方开始到26次方 { a[i]=a[i-1]*2; } for(int i=26;i>=2;i--) { if(n>=a[i])//找到一个就输出,并减去 { n-=a[i]; cout<<a[i]<<' '; } if(n==0)return 0; } return 0; } ``` 求关注
by zyhe2013 @ 2023-09-13 20:26:30


@[zyhe2023](/user/905073) 已关
by bohemiao @ 2023-09-13 22:14:25


|