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?
Two integers a, b(0<=a<=b<1000000000), about 100000 cases, end with EOF.
One answer per line.
1 2 1 3 1 4 1 6
0 2 3 6
题解转自 kk303
.常规的把握是求0~a-1的..与0~b的.... 再用后者减去前者得到答案...
通过观察..问题可以转化为..求a加到b的不进位二进制数..然后再通过至右向左的进位统计二进制的进位次数...再转化..就是求从a~b这些数...每一位有多少个1.....
如从0~3...表示成不进位的二进制数位22...再对22进位成合法的二进制数...22 -> 30 , 30 -> 110...一共进位两次.....
那么如何统计每一位上1的个数呢?通过几次演算..不难发现..从0+1+2+....x...当x为2^p-1时...该二进制数为2^p 2^p 2^p...
如0加到3为22.....0加到7为444...0加到15为8888.....
那么如何求不是2^p-1的数呢?
比如说10....比10小的最大2^p-1数是7...所以可以先得到0加到7的情况...444...还剩下了8,9,10没有加..而8,9,10若是去掉最高位的1..不就是0加到2的情况...
所以0加到10的不进位二进制数为444(0加到7)+300(8,9,10的高位)+011(0加到2)=755...
但注意...结果并不是数出0加到a-1的进位数s1...数出0到b的进位数s2...s2-s1....而是算出0加到a-1和0到b的不进位二进制数..用后者减去前者之后..再进行进位统计...
#include<fstream> #include<iostream> #include<cstdio> #include<cstring> #define FOR(i,a,b) for(int i=a;i<=b;++i) #define clr(f,z) memset(f,z,sizeof(f)) #define LL long long #define ll(x) (1<<x) using namespace std; const int mm=66; LL f1[mm],f2[mm]; void get(LL*f,LL x) { clr(f,0); int p=30; while(x>0)///统0-x的和 { while(x<ll(p))--p; FOR(i,0,p-1)f[i]+=ll(p-1); f[p]+=x+1-ll(p); x-=ll(p); } } int main() { LL a,b; while(cin>>a>>b) {clr(f1,0);clr(f2,0); get(f1,a-1);get(f2,b); FOR(i,0,mm-1) f2[i]-=f1[i]; LL ans=0; FOR(i,0,mm-1) { ans+=f2[i]/2; f2[i+1]+=f2[i]/2; } cout<<ans<<endl; } }