Sum in Binary Tree

Revision en1, by thomas2, 2026-02-13 09:12:16

Start from the n, shift right per bit, and sum all values until n is zero, then it is the ans.

#include <iostream>

void from_n() {
	long long n = 0;
	long long ans = 0;
	
	std::cin >> n;
	
	while (n) {
		ans += n;
		n >>= 1;
	}
 
	std::cout << ans << '\n';
}
int main(int argc, char *argv[]) {

    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
 
    int t; 
    std::cin >> t;
	
	while (t) {
		from_n();
		--t;
	}
	
 
	return 0;
}

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English thomas2 2026-02-13 09:12:16 516 Initial revision (published)