CF 1362C Johnny and Another Rating Drop

传送门

题目:给定一个数n,问(0~n)相邻两个数之间二进制位不同个数的总和。

思路:看出规律,把n转化为二进制,如果该二进制位处于第x位且为1,则它的贡献为2^(x) - 1,累加所有贡献即可。

 1 #include<iostream>
 2 #include<string>
 3 #include<vector>
 4 #include<cstdio>
 5 
 6 #define ll long long
 7 #define pb push_back
 8 
 9 using namespace std;
10 
11 const int N = 1e6 + 10;
12 
13 void solve()
14 {
15     int T;
16     cin >> T;
17     while(T--){
18         ll n, dif;
19         cin >> n;
20 
21         dif = 0;
22         for(int i = 0; i <= 61; ++i){
23             ll x = (((n >> i) & 1) << (i + 1));
24             dif += x - (x != 0);
25         }
26 
27         //cout << "dif = " << dif << endl;
28         cout << dif << endl;
29     }
30 }
31 
32 int main() {
33 
34     ios::sync_with_stdio(false);
35     cin.tie(0);
36     cout.tie(0);
37     solve();
38     //cout << "ok" << endl;
39     return 0;
40 }

 

posted @ 2020-08-16 15:20  SummerMingQAQ  阅读(188)  评论(0编辑  收藏  举报