D - Fast Bit Calculations

Description

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

c-free 中輸入用I64d 提交答案時改成lld

#include<stdio.h>
#include<math.h>
#include <algorithm>
using namespace std;
typedef long long lld;
int main()
{
	int r,ca=1;
	lld n,m;
	scanf("%d",&r);
	while(r--)
	{
		scanf("%lld",&n);
		
	    if(!n)  printf("Case %d: 0\n",ca++);
	    else
		{
    		for(int i=30;i>=0;i--)
			if((1<<i)&n)
			{
				m=i;
				break;
			}

		  lld sum=0;
		  lld q,p;
		  for(int i=1;i<=m;i++)
		  {
		    lld t=1;
			for(int j=1;j<=i;j++) 
			   t*=2;
	        q=t*2;
			p=t/2;
				
			sum+=((n+1)/q)*p;
            if((n+1)%q > q-p)	
			sum+=(n+1)%q-(q-p);
	      }
		  printf("Case %d: %lld\n",ca++,sum);		
    	}	
	}			
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章