首页 > 代码库 > UVA - 11645 Bits
UVA - 11645 Bits
Description
Problem J
Bits
Input: Standard Input
Output: Standard Output
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 it‘s 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 toN.
Examples:
Number Binary Adjacent Bits
12 1100 1
15 1111 3
27 11011 2
Input
For each test case, you are given an integer number (0 <= N <= ((2^63)-2)), as described in the statement. The last test case is followed by a negative integer in a line by itself, denoting the end of input file.
Output
For every test case, print a line of the form Case X: Y, where X is the serial of output (starting from 1) and Y is the cumulative summation of all adjacent bits from 0 to N.
Sample Input Output for Sample Input
0 6 15 20 21 22 -1 | Case 1: 0 Case 2: 2 Case 3: 12 Case 4: 13 Case 5: 13 Case 6: 14 |
题意:统计0-n中每个数存在两个连续的1的总个数。
思路:和的思路是一样的,也是枚举两个1的位置。 注意当11出现的位置和原数一样的时候,还要考虑+1或者+2的情况,还有就是用两个较大的数来储存结果。
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> using namespace std; long long aa,bb; void cal(long long n) { bb += n; if (bb >= (1000000000000ll)) { aa += bb / (1000000000000ll); bb %= (1000000000000ll); } } int main() { int cas = 1; long long n; long long a,b,c,m; while (cin >> n && n >= 0) { aa = bb = 0; m = 1, a = n; for (int i = 0; i < 62; i++) { cal((n>>2)*m); if ((n & 3) == 3) cal((a&((1ll<<i)-1))+1); m <<= 1; n >>= 1; } printf("Case %d: ", cas++); if(aa) { cout << aa; printf("%012lld\n",bb); } else cout<<bb<<endl; } return 0; }
UVA - 11645 Bits