ให้ n หาจำนวนจำนวนเต็ม 1 ถึง n ที่มีจำนวนบิต 1 (set bits) เป็นเลขคี่
ตัวอย่าง:
Input: n = 10 Output: 5
อัลกอริทึม
- ฟังก์ชันนับ set bits: วนหาร 2 นับเศษ 1
- count = 0
- วน i = 1 ถึง n:
- ถ้า setBits(i) % 2 == 1 count++
- คืนค่า count
การเขียนโปรแกรม C++
#include <bits/stdc++.h> using namespace std; int getSetBitsCount(int n) { int count = 0; while (n) { if (n % 2 == 1) count++; n /= 2; } return count; } int getOddSetBitsIntegerCount(int n) { int count = 0; for (int i = 1; i <= n; i++) { if (getSetBitsCount(i) % 2 == 1) count++; } return count; } int main() { int n = 10; cout << getOddSetBitsIntegerCount(n) << endl; return 0; }
ผลลัพธ์
5