2 solutions

  • 1
    @ 2024-12-7 21:18:31

    一定要开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
      @ 2024-11-30 14:35:37

      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;
      }
      
      
      • @ 2024-11-30 14:48:56

        这里再讲一下lowbit的原理

        我们知道,负数在位运算中以补码(即反码+1)的形式存在。
        那么,不考虑符号位,x&x的反码应该为0,
          反码+1时,若原码出现1,那么反码的0就会变成1(也许会有超长进位),与原码一致,相与为1,
          所以在且仅在长进位的终点(即原码为1的位置)会出现一个1,其余均为0
        
    • 1

    Information

    ID
    1150
    Time
    1000ms
    Memory
    128MiB
    Difficulty
    9
    Tags
    (None)
    # Submissions
    118
    Accepted
    12
    Uploaded By