poj 2453

显然是位操作题

做得有点没效率

考虑三种情况:

  1. 从低位读起,第一个读到的1后是0(例*0010*,则处理后为*0100*)
  2. 从低位读起,读到一串1,分两种情况,a。最低位为1(例*0111,处理后为*1011);b。最低位为0(例*001110,处理后为*010011
#include<stdio.h>
#include<string.h>
int main()
{
	int i,t;
	long n,temp,bite[25],num[25]={0,1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072,262144,524288,1048576,2097152,4194304};
	while(scanf("%ld",&n)!=EOF,n)
	{
		memset(bite,0,sizeof(bite));
		for(i=1;i<25;i++)
			bite[i]=n&num[i];
		for(i=1;;i++)
			if(bite[i])   //读到1
			{
				t=i-1;
				if(bite[i+1])
				{
					for(i=i+1;;i++)  //2
						if(!bite[i])
						{
							n=n&(~num[i-1]);
							n=n|num[i];
							break;
						}
					if(t)   //t>0,则情况2.b
					{
						temp=n;
						temp=temp>>t;
						temp=temp&(~(~0<<(i-2-t)));
						n=n&(~0<<(i-2));
						n=n+temp;
					}
				}
				else if(!bite[i+1])   //情况1
				{
					n=n&(~num[i]);
					n=n|num[i+1];
				}
				break;
			}
		printf("%ld\n",n);
	}
	return 0;
}

不过别人还有简短的代码:

#include <stdio.h>
int main()
{
    int n,x;
    while(scanf("%d",&n),n)
    {
        x=n&-n;
        printf("%d\n",n+x+(n^n+x)/x/4);
    }
}

原文地址:https://www.cnblogs.com/submarinex/p/1941278.html