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