蓝桥杯试题 算法训练 二进制数数
时间限制:1.0s 内存限制:256.0MB
问题描述
给定L,R。统计[L,R]区间内的所有数在二进制下包含的“1”的个数之和。
如5的二进制为101,包含2个“1”。
输入格式
第一行包含2个数L,R
输出格式
一个数S,表示[L,R]区间内的所有数在二进制下包含的“1”的个数之和。
样例输入
2 3
样例输出
3
数据规模和约定
L<=R<=100000;
我的AC代码:
#include"iostream"
#include"stdio.h"
#include"stack"
using namespace std;
stack<int> p;
int a[11111];
int ans=0;
void change(int z) {
int k = 0;
while (z) {
p.push(z % 2);
z /= 2;
}
while (!p.empty()) {
a[k] = p.top();
k++;
p.pop();
}
for (int i = 0;i < k;i++) {
if (a[i] == 1)
ans++;
}
}
int main() {
int L, R;
cin >> L >> R;
for (int i = L;i <= R;i++) {
change(i);
}
cout << ans;
return 0;
}
提交之后倒是通过了,但是回头一看这有些复杂了。
进制这块掌握的不好,需要勤加练习。
附上两篇-大-佬-题解
#include<iostream>
using namespace std;
int counts = 0;
void DFS(int n);
int main()
{
int L,R;
cin >> L >> R;
for (;L != R + 1; ++L)
DFS(L);
cout << counts;
return 0;
}
void DFS(int n)
{
while (n)
{
if (n % 2)
++counts;
n = n / 2;
}
}
和这篇
#include <iostream>
using namespace std;
int main() {
int L,R,sum=0,t;
for(cin>>L>>R;L<=R;L++)
for(t=L;t!=0;t/=2)
sum+=t%2;
cout<<sum;
return 0;
}
总结
将十进制整数转换为二进制数并不是只能用栈来进行,之前我就是在这里有个误区,觉得二进制只能用栈来解决,只是栈的特性适合十转二的存取。
还有在这个题里面并不需要将转换出来的数存取下来,二进制中只有0和1 ,所以直接判断即可。
改进后的代码
#include"iostream"
#include"stdio.h"
using namespace std;
int ans=0;
void change(int z) {
int k = 0;
while (z) {
if (z % 2)//若if语句成立 即其中含1
ans++;
z /= 2;
}
}
int main() {
int L, R;
cin >> L >> R;
for (int i = L;i <= R;i++) {
change(i);
}
cout << ans;
return 0;
}