C - Count The Carries(南洋理工OJ)
C - Count The Carries
时间限制: | 3000 Ms |
内存限制: | 65535 Kb |
问题描述
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?
输入说明
About 100000 cases, end with EOF.
Two integers a, b(0<=a<=b<1000000000).
输出说明
For each case, print one integers representing the number of carries per line.
输入样例
1 2 1 3 1 4 1 6
输出样例
0 2 3 6
#include<stdio.h> #include<string.h> int sum1[32]; int sum2[32]; long long cal(int sum[],int n) { int i,j,m=n;// int yu,bi=1;//余数和对应二进制位的数值 for(i=0,j=0; m; i++,j++) //m记录循环的位数 { if(i==0) sum[i]=(n+1)/2; else { bi*=2;//不同位的一代表的数 yu=(n-bi+1)%(2*bi); if(yu>bi)yu=bi; sum[i]=yu+(n-bi+1-yu)/(2*bi)*bi; //printf("%d %d\n",yu,bi); } m>>=1; //printf("%d %d\n",i,sum[i]); } //printf("%d %d\n\n",i,j); return 0; } int main() { int a,b,m; int jw; int i,j; long long sumx; while(scanf("%d %d",&a,&b)!=EOF) { if(a==0)a++; if(b==0)b++; memset(sum1,0,sizeof(sum1)); memset(sum2,0,sizeof(sum2)); cal(sum1,a-1); cal(sum2,b); m=b; for(i=0,j=0;m;i++,j++) { sum2[i]=sum2[i]-sum1[i]; m>>=1; } jw=0; sumx=0; for(i=0; i<j; i++) { sum2[i]+=jw; jw=sum2[i]/2; sumx+=jw; } while(jw>=2) { jw/=2; sumx+=jw; } printf("%lld\n",sumx); } return 0; }