# C - Count The Carries

 时间限制: 3000 Ms 内存限制: 65535 Kb

### 问题描述

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？

### 输入说明

About 100000 cases, end with EOF.

Two integers a, b（0<=a<=b<1000000000).

### 输出说明

For each case, print one integers representing the number of carries per line.

### 输入样例

1 2
1 3
1 4
1 6


### 输出样例

0
2
3
6

#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <string.h>
using namespace std;

void calc(int num[],int n)//计算0~n所以数中累加的各位二进制1的个数
{
for(int i=0;i<63;i++)num[i]=0;
int tmp=1;
n++;
for(int i=0;i<63;i++)
{
if(tmp>n)break;
tmp*=2;
num[i]+=(n-n%tmp)/2;
if(n%tmp > tmp/2)num[i]+=n%tmp-tmp/2;
}
}
int num1,num2;
int main()
{
int a,b;
while(scanf("%d%d",&a,&b)==2)
{
calc(num1,a-1);
calc(num2,b);
for(int i=0;i<63;i++)num2[i]-=num1[i];
long long ans=0;
for(int i=0;i<63;i++)
{
ans+=num2[i]/2;
num2[i+1]+=num2[i]/2;
}
printf("%lld\n",ans);
}
return 0;
}

posted on 2013-05-16 22:21  kuangbin  阅读(1417)  评论(0编辑  收藏  举报

JAVASCRIPT: