Codeforces Round #647 (Div. 2) C Johnny and Another Rating Drop(二進制有關題目)

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),求和即可

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章