Codeforces #647 C. Johnny and Another Rating Drop(思维,规律)

Johnny and Another Rating Drop

题目大意:(文末有原题)

给出一个数n,输出0~n相邻两个数间的差异位数的总和;

思路:

0 0000

1 0001

2 0010

3 0011

4 0100

5 0101

6 0110

7 0111

8 1000

通过举例可得:

对于第一位,变化为 010101010...周期为2;

对于第二位,变化为 001100110...周期为4;

对于第三位,变化为 000011110...周期为8;

很容易发现第k位的周期为2^k;

因此,如果第i位上是1,则需要加上2^i-1,所以只需判断每一位是否为1,如果第i位为1,则加上2^i -1;

代码:

#include <iostream>
using namespace std;
typedef long long ll;

void solve() {
	ll n;
	cin >> n;
	ll ans = 0;
	
	for(int i = 0; i < 60; i++)
		if(n & (1LL << i))			//1LL:1LL是使转变位long long 类型,防止了计算溢出; 
			ans += (1LL << (i + 1)) - 1;
			
	cout << ans << endl;
}

int main() {
	int t;
	cin >> t;
	
	while(t--) {
		solve();
	}
	
	return 0;
} 

题目:

The last contest held on Johnny's favorite competitive programming platform has been received rather positively. However, Johnny's rating has dropped again! He thinks that the presented tasks are lovely, but don't show the truth about competitors' skills.

The boy is now looking at the ratings of consecutive participants written in a binary system. He thinks that the more such ratings differ, the more unfair is that such people are next to each other. He defines the difference between two numbers as the number of bit positions, where one number has zero, and another has one (we suppose that numbers are padded with leading zeros to the same length). For example, the difference of 5=101(2) and 14=1110(2) equals to 3, since 0101 and 1110 differ in 3 positions. Johnny defines the unfairness of the contest as the sum of such differences counted for neighboring participants.

Johnny has just sent you the rating sequence and wants you to find the unfairness of the competition. You have noticed that you've got a sequence of consecutive integers from 0 to n. That's strange, but the boy stubbornly says that everything is right. So help him and find the desired unfairness for received numbers.

输入:

The input consists of multiple test cases. The first line contains one integer t (1≤t≤10000) — the number of test cases. The following tt lines contain a description of test cases.

The first and only line in each test case contains a single integer nn (1≤n≤10^18).

输出:

Output tt lines. For each test case, you should output a single line with one integer — the unfairness of the contest if the rating sequence equals to 0, 1, ..., n−1,n.

样例:

Input:

5
5 ------------------------ 8
7 ------------------------ 11
11 ---------------------- 19
1 ------------------------ 1
2000000000000 ---- 3999999999987

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值