从a加到b,统计二进制进位总次数,纯粹暴力,肯定超时。
所以转换成统计从0-a二进制表达的各位1的个数,0-b各位的1的个数,后者减前者对应位,即可求出每位有多少个1。然后当前位1的个数/2,就是当前位的总进位数,后面的加上前一位答案除二,再除二,累加即可推出总数。
那么如何统计每一位上1的个数呢???卡壳卡了两个小时……
以下是规律:
1 1 1
10 11 2
11 22 3
100 122 4
101 223 5
110 333 6
111 444 7
1000 1444 8
1001 2445 9
1010 3455 10
1011 4466 11
1100 5566 12
1101 6667 13
1110 7777 14
1111 8888 15
0位上每2个就有1个1
1位上每4个就有2个1
2位上每8个就有4个1
这就妥妥可以求总数了
void getn (int a[],int n) {
int t=1; n++;
for (int i=0; i<65; i++) {
if (t>n) { break; }
t*=2;//每增大一位,循环节大一倍
a[i]+= (n/t) * (t/2);
//余数大于t/2的话,后面还有n% (t/2)个1
if (n%t>t/2) {a[i]+=n% (t/2);}
}
}
#include<stdio.h>
#include<iostream>
#include<math.h>
#include<string.h>
#include<iomanip>
#include<stdlib.h>
#include<ctype.h>
#include<algorithm>
#include<deque>
#include<functional>
#include<iterator>
#include<vector>
#include<list>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<sstream>
#define CPY(A, B) memcpy(A, B, sizeof(A))
typedef long long LL;
typedef unsigned long long uLL;
const int MOD = 1e9 + 7;
const int INF = 0x3f3f3f3f;
const LL INFF = 0x3f3f3f3f3f3f3f3fLL;
const double EPS = 1e-9;
const double OO = 1e20;
const double PI = acos (-1.0);
int dx[]= {0,1,1,1,0,-1,-1,-1};
int dy[]= {1,1,0,-1,-1,-1,0,1};
using namespace std;
int num1[66],num2[66];
void getn (int a[],int n) {
int t=1; n++;
for (int i=0; i<65; i++) {
if (t>n) { break; }
t*=2;//每增大一位,循环节大一倍
a[i]+= (n/t) * (t/2);
//余数大于t/2的话,后面还有n% (t/2)个1
if (n%t>t/2) {a[i]+=n% (t/2);}
}
}
int main() {
int a,b; LL sum;
while (~scanf ("%d%d",&a,&b) ) {
memset (num1,0,sizeof (num1) );
memset (num2,0,sizeof (num2) );
getn (num1,a-1);//do not miss a
getn (num2,b);
for (int i=0; i<65; i++) {num2[i]-=num1[i];}
sum=0;
for (int i=0; i<65; i++) {
sum+=num2[i]/2;
num2[i+1]+=num2[i]/2;
}
cout<<sum<<endl;
}
return 0;
}