2 solutions
-
1
一定要开long long!!!
#include<bits/stdc++.h> using namespace std; //int lowbit(int x) //{ // return x&-x; //} //知道__builtin_popcount()可以用 int popcount(long long y)//1的个数 { int res = 0; while(y) { if(y%2) { res++; } y/=2; } return res; } int main() { long long t, n; cin >> t; for(int i = 1; i <= t; i++) { cin >> n; if(popcount(n)>=3) { cout << "No,Commander" << endl; } if(popcount(n) == 1) { cout << n+1 << endl; } if(popcount(n) == 2) { cout << n + (n&-n) << endl;//加括号是应为位运算优先级很低 } // ^ } // | return 0; // lowbit(n) }
-
0
P4951
如果一开始用暴力,顶多60
分享一个函数:
__builtin_popcount()
就是popcount函数 注意到在popcount函数<3时 分两种情况:1.popcount为1
此时只需要+1即可 (若末位为0,则+1仍仅有2个1,不影响)
2.popcount为2
此时不难发现,我们不能盲目+1(会出现3个),最好的方法是将第一个出现的01区间变为10,寻找最末位的1,等价于x&-x,即lowbit. 附上代码:
#include<bits/stdc++.h> using namespace std; int main(){ int t; scanf("%lld",&t); while(t--){ long long a; scanf("%lld",&a); if(__builtin_popcountll(a)>=3){ printf("No,Commander\n"); } else if(__builtin_popcountll(a)==1){ printf("%lld\n",a+1); } else{ printf("%lld\n",a+(a&-a)); } } return 0; }
- 1
Information
- ID
- 1150
- Time
- 1000ms
- Memory
- 128MiB
- Difficulty
- 9
- Tags
- (None)
- # Submissions
- 118
- Accepted
- 12
- Uploaded By