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



转载于:https://www.cnblogs.com/AC-dream/p/5716407.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值