light oj 1032 - Fast Bit Calculations

1032 - Fast Bit Calculations
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

 数位DP.

dp[pos][sum][st]:当前位数为pos时,sum为“11”有多少个,st为前一位为0或1;

#include<iostream>
using namespace std;
#include<string.h>
long long dp[50][50][2];
int dight[50];
long long dfs(int pos,int sum,int st,bool flag)
{  int i;
   long long ans=0;
    if(pos==-1)return sum;
    if(!flag&&dp[pos][sum][st]!=-1)return dp[pos][sum][st];
    int u=flag?dight[pos]:1;
    for(i=0;i<=u;i++)
        ans=ans+dfs(pos-1,sum+(st&&i==1),i,flag&&i==u);
    if(!flag)dp[pos][sum][st]=ans;
    return ans;
}
long long fun(long long n)
{
    int len=0;
    while(n)
    {
        dight[len++]=n%2;
        n=n/2;
    }
    dfs(len-1,0,0,1);
}
int main()
{
    int t,i;
    long long n;
    cin>>t;
    for(i=1;i<=t;i++)
    { memset(dp,-1,sizeof(dp));
      cin>>n;
      cout<<"Case "<<i<<":"<<" "<<fun(n)<<endl;
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值