A. And Then There Were K
题意:
给你一个n,让你求一个k,使得满足下列式子:
n & (n-1) & (n-2) &…&(k) = 0
问k最小是多少?
题解:
找规律
比如n的二进制为:1111
那么n-1就是:1110
n-2就是:1101
…
你会发现n-1是最后一位和n不一样,n-2是倒数第二位不一样,在&下,不同为0,所以k最大就是0111,就是第一位不一样,其余都为1
代码:
#include<bits/stdc++.h>
#define debug(a,b) printf("%s = %d\n",a,b);
typedef long long ll;
using namespace std;inline int read(){int s=0,w=1;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();//s=(s<<3)+(s<<1)+(ch^48);return s*w;
}
int main()
{int t;cin>>t;while(t--){ll n;cin>>n;ll ans=1;int f=0;ll i;for(i=30;i>=0;i--){if(f==0&&(n&(1<<i))){f=1;ans=(1<<i);continue;}if((n&(1<<i))==0){if(f==0)continue; break;}}cout<<ans-1<<endl;} return 0;
}