Codeforces Round #721 (Div. 2) A. And Then There Were K

题意:

给出一个数 n n n ,求最大的 k k k 使得 n & ( n − 1 ) & ( n − 2 ) . . . & k = 0 n \& (n-1) \& (n-2) ...\&k =0 n&(n1)&(n2)...&k=0

题解:

本蒟蒻只会打表找规律。看完正解直呼妙啊。

n n n 转换成二进制数来看,假设最高位的 1 1 1在第 i i i 位,那么想要消除掉这个 1 1 1 , k k k 肯定要 ≤ 2 i − 1 \leq 2^i-1 2i1 ,也就是说,必须要有数在第 i i i 位为 0 0 0 ,那么对于所有 ≥ 2 i \geq 2^i 2i 的数,肯定是能把剩下的 1 1 1 消除掉的,所以 k最大就是 2 i − 1 2^i-1 2i1

代码:

#pragma GCC diagnostic error "-std=c++11"
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<map>
#include<stack>
#include<set>
#include<ctime>
#define iss ios::sync_with_stdio(false)
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
typedef pair<int,int> pii;
const int mod=1e9+7;
const int MAXN=2e5+5;
const int inf=0x3f3f3f3f;
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        int pos=0;
        for(int i=31;i>=0;i--)
        {
            if((n>>i)&1)
            {
                pos=i;
                break;
            }
        }
        cout<<(1<<pos)-1<<endl;
    }
}
posted @ 2021-05-22 12:25  TheBestQAQ  阅读(43)  评论(0)    收藏  举报