跳到正文

题解

题解:P14074 [GESP202509 五级] 有趣的数字和

hashing约 1 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年5月2日
篇幅
约 1 分钟
题目
P14074

版本

  1. v4当前
  2. v3
  3. v2
  4. v1

前言

我考场上并没过,因为我不会拼__builtin_popcount。。。

题目大意

给定两个数,求这两个数的区间里个数满足用二进制表示中 1 的个数为奇数的和。

题目思路

我们对每个数用 __builtin_popcount 函数统计这个数用二进制表示出来中 1 的个数是否为奇数,判断完之后再累加符合条件的数的和即可。

我来解释一下为什么暴力枚举可以通过这道题:

因为对于 __builtin_popcount 函数,编译器会将这个函数直接翻译成 CPU 单条指令,是 O(1)O(1) 的时间复杂度。这样一共 O(n)O(n) 的时间复杂度刚好能够卡着时限通过本题。

代码

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	int l, r;
	cin >> l >> r;
	int ans = 0;
	for(int i = l; i <= r; i ++) {
		if(__builtin_popcount(i) % 2 == 1) {
			ans += i;
		}
	}
	cout << ans;
	return 0;
}
原文