简答题
偏难
#7109
计算好数 若将一个正整数化为二进制数,在此二进制数中,我们将数字1的个数多于数字0的个数的这类二进制数称为好数。 例如: (13)10 = (1101)2,其中…
计算好数
若将一个正整数化为二进制数,在此二进制数中,我们将数字1的个数多于数字0的个数的这类二进制数称为好数。
例如:
(13)10 = (1101)2,其中1的个数为3,0的个数为1,则此数是好数;
(10)10 = (1010)2,其中1的个数为2,0的个数也为2,则此数不是好数;
(24)10 = (11000)2,其中1的个数为2,0的个数为3,则此数不是好数;
对于给定的N,写程序求出1~N之中(包括1与N)中的好数个数。
时间限制:1000
内存限制:65536
输入
一个整数,题目中的N(N ≤ 1000)
输出
一个整数,表示1~N之中(包括1与N)中的好数个数
样例输入
10
样例输出
5
答案与解析
正确答案:<pre class="brush:cpp;toolbar:false">//参考代码1
#include <cstdio>
int main() {
int j;
scanf("%d", &j);
int t;
int s = 0, c = 0, w = 0;
for (int n = 1; n <= j; n++) {
for (int i = n; i; i /= 2) {
t = i % 2;
if (t == 1) {
s++;
} else {
c++;
}
}
if (s > c) {
w++;
}
s = 0;
c = 0;
}
printf("%d", w);
return 0;
}</pre><pre class="brush:cpp;toolbar:false">//参考代码2
#include <algorithm>
#include <iostream>
using namespace std;
int a[12], b[12];
int main() {
int n;
cin >> n;
int ans = 0;
for (int i = 1; i <= n; i++) {
int t = i, a = 0, b = 0;
while (t) {
if (t & 1)
a++;
else
b++;
t >>= 1;
}
if (a > b)
ans++;
}
cout << ans;
return 0;
}</pre><p><br/></p>
这道题暂未补解析。