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?
 


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,让你计算从a到b之间的数的二进制数之和进位的总次数。
将每一个数拆成二进制数,那么第一位数1的总数就是从a到b第一位是1的数量之和,那么第一位进位的数量为第一位是1的总数/2;
第二位1的总数就是从a到b第二位是1的数量之和加上由第一位进位的数量;
第三位1的总数就是从a到b第三位是1的数量之和加上由第二位进位的数量;
.
.
.
如何求每一位上1的总数?0到8的二进制数如下:
8 7 6 5 4 3 2 1 0
0 0 0 0 0 0 0 0 0     (0)
0 0 0 0 0 0 0 0 1   (1)
0 0 0 0 0 0 0 1 0   (2)
0 0 0 0 0 0 0 1 1   (3)
0 0 0 0 0 0 1 0 0   (4)
0 0 0 0 0 0 1 0 1   (5)
0 0 0 0 0 0 1 1 0   (6)
0 0 0 0 0 0 1 1 1   (7)
0 0 0 0 0 1 0 0 0   (8)
第一位是10交替出现,第二位是0011交替出现,第三位是00001111交替出现......
那么规律就出来了。

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
    long long a,b,sum;
    long long s[70],x[70];
    while(cin>>a>>b)
    {
        memset(s,0,sizeof(s));
        memset(x,0,sizeof(x));
        sum=0;
        b++;
        if(a==b)
        {
             cout<<"0"<<endl;
             continue;
        }
        int n=b,k=2;
        for(int i=0;i<70;i++)
        {
            s[i]=a/k*k/2+(a%k>=k/2?a%k-k/2:0);//求第i位是1的个数总和
            x[i]=b/k*k/2+(b%k>=k/2?b%k-k/2:0);
            k*=2;
            n/=2;
            if(!n)
            break;
        }
        for(int i=0;i<70;i++)
        {
            sum+=(x[i]-s[i])/2;
            x[i+1]+=(x[i]-s[i])/2;
        }
        cout<<sum<<endl;
    }
    return 0;
}
求A到B之间二进制的1的个数(注意:不包括A,B本身 1<=A<=B<=10^16

同样的规律

输入

1000000000000000 10000000000000000
2 12
9007199254740992 9007199254740992

输出

239502115812196372
21
1


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值