1. 程式人生 > 實用技巧 >CF 1362C Johnny and Another Rating Drop

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 }