CF 1362C Johnny and Another Rating Drop

傳送門ios

題目:給定一個數n,問(0~n)相鄰兩個數之間二進制位不一樣個數的總和。spa

思路:看出規律,把n轉化爲二進制,若是該二進制位處於第x位且爲1,則它的貢獻爲2^(x) - 1,累加全部貢獻便可。code

 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 }
相關文章
相關標籤/搜索