题目链接
The last contest held on Johnny’s favorite competitive programming platform has been received rather positively. However, Johnny’s rating has dropped again! He thinks that the presented tasks are lovely, but don’t show the truth about competitors’ skills.
The boy is now looking at the ratings of consecutive participants written in a binary system. He thinks that the more such ratings differ, the more unfair is that such people are next to each other. He defines the difference between two numbers as the number of bit positions, where one number has zero, and another has one (we suppose that numbers are padded with leading zeros to the same length). For example, the difference of 5=1012 and 14=11102 equals to 3, since 0101 and 1110 differ in 3 positions. Johnny defines the unfairness of the contest as the sum of such differences counted for neighboring participants.
Johnny has just sent you the rating sequence and wants you to find the unfairness of the competition. You have noticed that you’ve got a sequence of consecutive integers from 0 to n. That’s strange, but the boy stubbornly says that everything is right. So help him and find the desired unfairness for received numbers.
The input consists of multiple test cases. The first line contains one integer t (1≤t≤10000) — the number of test cases. The following t lines contain a description of test cases.
The first and only line in each test case contains a single integer n (1≤n≤1e18).
Output t lines. For each test case, you should output a single line with one integer — the unfairness of the contest if the rating sequence equals to 0, 1, …, n−1, n.
5
5
7
11
1
2000000000000
8
11
19
1
3999999999987
简单位运算题~
_
_
b
u
i
l
t
i
n
_
p
o
p
c
o
u
n
t
l
l
\_\_builtin\_popcountll
__builtin_popcountll 统计长整型数的二进制的
1
1
1 的个数,为方便书写我简记为
b
b
b
我们不难发现答案
a
n
s
=
b
(
1
⊕
2
)
+
b
(
2
⊕
3
)
+
⋯
+
b
(
(
n
−
1
)
⊕
n
)
=
2
∗
n
−
b
(
n
)
ans=b(1⊕2)+b(2⊕3)+\cdots+b((n-1)⊕n)=2*n-b(n)
ans=b(1⊕2)+b(2⊕3)+⋯+b((n−1)⊕n)=2∗n−b(n),具体证明可以看题解,AC代码如下:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
main(){
ll n,t;
cin>>t;
while(t--){
cin>>n;
cout<<2*n-__builtin_popcountll(n)<<endl;
}
}