HDU 4588

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?

Input

Two integers a, b(0<=a<=b<1000000000), about 100000 cases, end with EOF.

Output

One answer per line.

Sample Input

1 2
1 3
1 4
1 6

Sample Output

0
2
3
6
题意大致是: 给a b;求由a到b 的二进制数共进位几次;
00000
00001
00010
00011
00100
00101
00110
00111
01000
找规律:
第一位的循环节是2^1,1出现的次数为2^0;
第二位循环节是2^2,1 出现的次数2^1;
.

.
.
.
第n位循环节是2^n 1出现的次数2^n-1;
由此可知;
求出0到a-1 的 转化成二进制数每一位1的个数;
例如 3 记作a
000
001
010
011
第一位1的个数为2;
第二位1的个数为2
第三位1的个数为0;
第一位: 先看他出现了几次循环节 (a+1)/2^1;
1出现了几次 int((a+1)/2^1)*2^0;
如果不加int 转换 可能(a+1)/2^1 出现小数;
上式化简是 (a+1)/2;是不能化简的;
如果 t=(a+1)%2^n
如果t>2^n-1;那么1的个数还要再加t-2^n-1;个
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ll;
ll  num1[100];
ll  num2[100];
ll  num[100];
ll slove(ll a,ll  *b)
{
    memset(b,0,sizeof(b));
    ll t=1;
    for(int j=0; j<63; j++)
    {
        t=t*2;
        b[j]=ll ((a+1)/t)*(t/2);
        ll nnum=(a+1)%t;
        if(nnum>t/2)
        {
            b[j]+=nnum-t/2;
        }
    }
}
int main()
{
    ll  a,b;
    while(scanf("%I64d%I64d",&a,&b)!=EOF)
    {
        memset(num,0,sizeof(num));

        slove(a-1,num1);
        slove(b,num2);
        for(int i=0; i<63; i++ )
        {
            num[i]=num2[i]-num1[i];
        }
        ll sum=0;
        for(int i=0; i<63; i++)
        {
            sum+=num[i]/2;
            num[i+1]+=num[i]/2;// 前一位进2位此位进1;
        }
        printf("%I64d\n",sum);
    }
    return 0;
}



posted @ 2016-07-28 21:52  AC_dream  阅读(216)  评论(0编辑  收藏  举报