A. And Then There Were K

Posted Jozky86

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了A. And Then There Were K相关的知识,希望对你有一定的参考价值。

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;
}

以上是关于A. And Then There Were K的主要内容,如果未能解决你的问题,请参考以下文章

cf 1524A And Then There Were K

越狱Season 1-Episode 11: And Then There Were 7-M

UVALive 3882 And Then There Was One

LA3882And then there was one

UVALive - 3882:And Then There Was One

G - And Then There Was One (约瑟夫环)