HDU 4588 统计二进制加法进位次数

Count The Carries


Problem Description
One day, Implus gets interested in binary addition and binary carry. He will transfer all decimal digits to binary digits to make the addition. Not as clever as Gauss, to make the addition from a to b, he will add them one by one from a to b in order. For example, from 1 to 3 (decimal digit), he will firstly calculate 01 (1)+10 (2), get 11,then calculate 11+11 (3),lastly 110 (binary digit), we can find that in the total process, only 2 binary carries happen. He wants to find out that quickly. Given a and b in decimal, we transfer into binary digits and use Implus's addition algorithm, how many carries are there?

 

统计用二进制从a加到b的进位次数

规律题,先统计出从a到b每一位上1的个数a[i],打表可发现每一位上0和1出现的规律

对第i位,进位次数为a[i]/2,每次进位会使高一位上多一个1,即a[i+1]+=a[i]/2


#include <cstdio>
#include <cstring>

int aa[100],bb[100];

void gettable(int n,int m)
{
	memset(aa,0,sizeof(aa));
	memset(bb,0,sizeof(bb));
	int t=1;
	n+=1;
	m+=1;
	for(int i=0;i<64;i++)
    {
        if(t>n)
			break;
        t*=2;
        aa[i]+=(n-n%t)/2;

        if(n%t>t/2)
			aa[i]+=n%t-t/2;

    }
    t=1;
    for(int i=0;i<64;i++)
    {
        if(t>m)
			break;
        t*=2;
        bb[i]+=(m-m%t)/2;
        if(m%t>t/2)
			bb[i]+=m%t-t/2;
    }
}

int main()
{
	int a,b;
	long long ans;
	while(scanf("%d%d",&a,&b)!=EOF)
	{
		gettable(a-1,b);
		for(int i=0;i<64;i++)
		{
			bb[i]-=aa[i];
		}
		ans=0;
		for(int i=0;i<64;i++)
		{
			ans+=bb[i]/2;
			bb[i+1]+=bb[i]/2;
		}
		printf("%I64d\n",ans);
	}

}


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值