http://codeforces.com/contest/1362/problem/C
給你一個數字n,現在從0中,我們全部化成二進制,然後相鄰之間的位數不同的相加後得到的就是最後的答案了。
榜一的神仙代碼,沒看懂
#include <bits/stdc++.h>
using namespace std;
long long f(long long n) {
return n == 0 ? 0 : n + f(n / 2);
}
int main() {
int t;
scanf("%d", &t);
while (t--) {
long long n;
scanf("%lld", &n);
printf("%lld\n", f(n));
}
return 0;
}
#include <bits/stdc++.h>
using namespace std;
int main(){
int t; cin>>t;
while(t--){
long long n; scanf("%lld", &n);
long long ans=0;
for(long long i=1; i<=1e18; i*=2){
ans+=n/i;
}
cout<<ans<<endl;
}
return 0;
}
最後一位每次都要變化,所以最後一位變化次數爲n,倒推倒數第二位變化次數就是n/2;第i位變化次數就是n<<(i-1),求和即可