Time Limit: 2 second(s) | Memory Limit: 32 MB |
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 | Output for Sample Input |
7 0 6 15 20 21 22 2147483647 | Case 1: 0 Case 2: 2 Case 3: 12 Case 4: 13 Case 5: 13 Case 6: 14 Case 7: 16106127360 |
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<set>
#include<map>
#define L(x) (x<<1)
#define R(x) (x<<1|1)
#define MID(x,y) ((x+y)>>1)
#define bug printf("hihi\n")
#define eps 1e-8
typedef long long ll;
using namespace std;
#define INF 0x3f3f3f3f
#define N 33
ll dp[N][N][2];
int bit[N];
ll dfs(int pos,int cur,int pre,bool bound)
{
if(pos==-1) return cur;
if(!bound&&dp[pos][cur][pre]>=0) return dp[pos][cur][pre];
ll ans=0;
int up=bound ? bit[pos]:1;
for(int i=0;i<=up;i++)
{
if(i&1)
ans+=dfs(pos-1,cur+pre,i,bound&&i==up);
else
ans+=dfs(pos-1,cur,i,bound&&i==up);
}
if(!bound) dp[pos][cur][pre]=ans;
return ans;
}
ll fdd(int n)
{
int len=0;
while(n)
{
bit[len++]=n%2;
n/=2;
}
return dfs(len-1,0,0,true);
}
int main()
{
int i,j,t,ca=0,n;
memset(dp,-1,sizeof(dp));
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
printf("Case %d: %lld\n",++ca,fdd(n));
}
return 0;
}