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 |
题意:给你一个数n,问你在二进制下1~n*有几对11。
一道数位dp。
dp[len][count][pre] len表示当前位数,count表示1~len位有几对“11”,pre表示上一位是什么。
#include <iostream>
#include <cstring>
using namespace std;
typedef long long LL;
LL dp[100][100][2];
LL dig[100];
LL dfs(int x , int pre , int flag , int count)
{
if(x == -1)
return count;
if(dp[x][count][pre] != -1 && !flag)
return dp[x][count][pre];
int n = flag ? dig[x] : 1;
LL sum = 0;
for(int i = 0 ; i <= n ; i++)
{
if(pre == 1 && i == 1)
sum += dfs(x - 1 , i , flag && i == n , count + 1);
else
{
sum += dfs(x - 1 , i , flag && i == n , count);
}
}
if(!flag)
dp[x][count][pre] = sum;
return sum;
}
LL Gets(int x)
{
memset(dig , 0 , sizeof(dig));
int len = 0;
while(x)
{
dig[len++] = (x & 1);
x >>= 1;
}
return dfs(len - 1 , 0 , 1 , 0);
}
int main()
{
int t;
cin >> t;
int ans = 0;
while(t--)
{
ans++;
int n;
cin >> n;
memset(dp , -1 , sizeof(dp));
cout << "Case " << ans << ": " << Gets(n) << endl;
}
return 0;
}