2013 ACM-ICPC南京全国邀请赛

Count The Carries

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中的所有数转成二进制,然后相加,求相加过程中有几次低位向高位进位
刚开始直接把所有数进行二进制转化,这想想肯定超时,后面推规律发现只要求的所有二进制相加后每一位的数进行处理即可以得到结果,但是求每一位上的1我还是用了转二进制的方法。。还是超时了。。换思路,转二进制肯定不行
要求几个数的二进制相加后每一位上的数值,列出几个数即可以发现规律
    00
    01
    10
    11
  100
  101
  110
  111
1000
1001
1010
1011
1100
1101
1110
1111
可以发现 :0位上每隔2数就有1个1
                   1位上每隔4数就有2个1
                   2位上每隔8数就有4个1
                   3位上每隔16数就有8个1
所以只要求每一位上1的个数之和,后面在处理就行
代码:
#include <iostream>
#include <stdio.h>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <vector>
#include <map>
using namespace std;
const int M=1e5+5;
const int mod=1e9+7;
int num1[70];
int num2[70];
void cal(int a[],int n)//0-n每个数位上1的和
{
	int i,temp;
	temp=1;
	n++;
	for(i=0;i<64;i++)
	{
		if(temp>n)break;
		temp*=2;
		a[i]+=(n/temp)*(temp/2);
		if(n%temp>temp/2)//余数大于temp/2,后面还有n%temp-temp个1
		  a[i]+=n%temp-temp/2;//或者a[i]+=n%(tmp/2);
	}
}
int main()
{
    int a,b,i;
    long long sum;
    while(scanf("%d%d",&a,&b)!=EOF)
    {
        memset(num1,0,sizeof(num1));
        memset(num2,0,sizeof(num2));
        cal(num1,a-1);
        cal(num2,b);
        for(i=0;i<64;i++)
        num2[i]-=num1[i];
        sum=0;
        for(i=0;i<63;i++)
        {
            sum+=num2[i]/2;
            num2[i+1]+=num2[i]/2;
        }
        printf("%lld\n",sum);
    }
    return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值