http://www.lightoj.com/volume_showproblem.php?problem=1042
代码:
#include<cstdio> #include<cstring> #include<iostream> #include<cmath> #include<string> #include<vector> #include<map> using namespace std; int Rint() { int x; scanf("%d", &x); return x; } #define FOR(i, a, b) for(int i=(a); i<(b); i++) #define REP(x) for(int i=0; i<(x); i++) #define int64 long long #define INF 1<<30 #define bug(s) cout<<#s<<"="<<s // 低位的一个01组合,变为10. 更低位的1全移到最末 int BitCount(unsigned int n) { n = (n & 0x55555555) + ((n >> 1) & 0x55555555) ; n = (n & 0x33333333) + ((n >> 2) & 0x33333333) ; n = (n & 0x0f0f0f0f) + ((n >> 4) & 0x0f0f0f0f) ; n = (n & 0x00ff00ff) + ((n >> 8) & 0x00ff00ff) ; n = (n & 0x0000ffff) + ((n >> 16) & 0x0000ffff) ; return n ; } int solve(int x) { int lowbit = x&(-x); int y = (-x)^lowbit; int lowzero = y&(-y); int ans = (x|lowzero)^(lowzero>>1); int cnt = BitCount((unsigned int)(ans&(lowzero-1))); ans = (ans|(lowzero-1))^(lowzero-1); ans|=(1<<cnt)-1; return ans; } int main() { int T = Rint(); for(int t=0; t<T; t++) { printf("Case %d: %d\n", t+1, solve(Rint())); } }