题目传送门
解题思路
注意到,由于没有重复的 ,所以 正好对应 二进制下的第 且为 的位。
于是我们首先将 转化为二进制,然后枚举它的第 位,同时将答案加上对应二进制位的位权即可。
可以在转换进制时直接倒序操作更便捷,注意位权从 开始。
数据较大,对于 C++ 语言需要开 unsigned long long。
代码呈现
C++
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cstring> // 不用万能头
using namespace std;
int main() {
unsigned long long x, ans = 0; // 开ull
cin >> x;
for (int i = 0; x; i ++) { // 从 0 开始
ans += i * (x % 2);
x /= 2;
}
cout << ans;
return 0;
}
Python
x = int(input())
ans = i = 0
while x:
ans += i * (x % 2)
x //= 2
i += 1
print(ans)
复杂度分析
程序的复杂度是 。
其他题解
如果你有其它解法,欢迎私信我,优秀的解法会在下方附上链接。欢迎投稿,私信时为方便,请按
/commit sol U522653 <题解文章(建议)/剪贴板(不建议)链接>
的格式。
目前还没有其他题解,快来投稿哇!