A bit is a binary digit, taking a logical value of either 1 or 0 (also referred to as "true" or "false" respectively). And every decimal number has a binary representation which is actually a series of bits. If a bit of a number is 1 and its next bit is also 1 then we can say that the number has a 1 adjacent bit. And you have to find out how many times this scenario occurs for all numbers up to N.
Examples:
Number Binary Adjacent Bits
12 1100 1
15 1111 3
27 11011 2
Input
Input starts with an integer T (≤ 10000), denoting the number of test cases.
Each case contains an integer N (0 ≤ N < 231).
Output
For each test case, print the case number and the summation of all adjacent bits from 0 to N.
Sample Input
7
0
6
15
20
21
22
2147483647
Sample Output
Case 1: 0
Case 2: 2
Case 3: 12
Case 4: 13
Case 5: 13
Case 6: 14
Case 7: 16106127360
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 #include<cstdlib> 5 #include<algorithm> 6 #include<cmath> 7 #include<queue> 8 #include<deque> 9 #include<set> 10 #include<map> 11 #include<ctime> 12 #define LL long long 13 #define inf 0x7ffffff 14 #define pa pair<int,int> 15 #define mkp(a,b) make_pair(a,b) 16 #define pi 3.1415926535897932384626433832795028841971 17 using namespace std; 18 inline LL read() 19 { 20 LL x=0,f=1;char ch=getchar(); 21 while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1;ch=getchar();} 22 while(ch>=‘0‘&&ch<=‘9‘){x=x*10+ch-‘0‘;ch=getchar();} 23 return x*f; 24 } 25 LL n,len,l,r; 26 LL f[50][2][50]; 27 int d[110]; 28 int zhan[50],top; 29 inline LL dfs(int now,int dat,int tot,int fp) 30 { 31 if (now==1)return tot; 32 if (!fp&&f[now][dat][tot]!=-1)return f[now][dat][tot]; 33 LL ans=0,mx=fp?d[now-1]:1; 34 for (int i=0;i<=mx;i++) 35 { 36 if (i==0)ans+=dfs(now-1,0,tot,fp&&i==d[now-1]); 37 else ans+=dfs(now-1,1,tot+(dat==1),fp&&i==d[now-1]); 38 } 39 if (!fp)f[now][dat][tot]=ans; 40 return ans; 41 } 42 inline LL calc(LL x) 43 { 44 if (x<=0)return 0; 45 LL xxx=x; 46 len=0; 47 while (xxx) 48 { 49 d[++len]=xxx%2; 50 xxx/=2; 51 } 52 LL sum=0; 53 for (int i=0;i<=d[len];i++)sum+=dfs(len,i,0,i==d[len]); 54 return sum; 55 } 56 main() 57 { 58 int T=read(),cnt=0; 59 while (T--) 60 { 61 r=read(); 62 if (r<l)swap(l,r); 63 memset(f,-1,sizeof(f)); 64 printf("Case %d: %lld\n",++cnt,calc(r)); 65 } 66 }
LightOj 1032