遇到了一个有意思的题目,有意思的点不在于题目本身,在于它的10进制转2进制。
题目传送门:B2140 二进制分类 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
想了很久才想出这个模板:
1 2 3 4 5 6 7 8 9 10 11
| int decToBin(int dec) { int result = 0, temp = dec, j = 1; while (temp) { result += j * (temp % 2); temp = temp / 2; j = j * 10; } return result; }
|
可以在草稿纸上演算一下。
code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| #include <cstdio> int n, ansa, ansb; int decToBin(int dec) { int result = 0, temp = dec, j = 1; while (temp) { result += j * (temp % 2); temp = temp / 2; j = j * 10; } return result; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { int tmp = decToBin(i), n1 = 0, n0 = 0; while (tmp != 0) { if (tmp % 10 == 1) { n1++; } else { n0++; } tmp /= 10; } if (n1 > n0) { ansa++; } else { ansb++; } } printf("%d %d", ansa, ansb); return 0; }
|
This article was written on 2022/7/10.