数字统计
题目描述
请统计某个给定范围[L, R][L,R]的所有整数中,数字 22 出现的次数。
比如给定范围[2, 22][2,22],数字22 在数 22中出现了 11 次,在数1212 中出现 11 次,在数 2020 中出现 11次,在数 21 中出现 11 次,在数 2222 中出现 22次,所以数字22 在该范围内一共出现了 66次。
输入格式
22个正整数 LL 和 RR,之间用一个空格隔开。
输出格式
数字 22出现的次数。
一、思路1
首先将每一个数字添加进来 然后进行转换成字符串char类型
以下为将整型转换成char类型数组
int a = 123;
char str[10];
_itoa_s(a, str, 10);
然后用字符串拼接 全部遍历结束之后 就开始一个一个的判断 遍历整个字符串数组 遇到2就累加
#include<iostream>
#include <cstring>
#include <string.h>
#include<string>
using namespace std;
char b[300000];
int main() {
int l, r, count = 0;
string s = "";
cin >> l >> r;
for (int i = l; i <= r; i++)
{
string s1 = to_string(i);
s = s + s1;
}
strcpy_s(b, s.c_str());
for (int j = 0; j < strlen(b); j++)
{
if (b[j] == '2') {
count++;
}
}
cout << count;
return 0;
}
但结果是80分 因为最后一个时间超长 花了1.2s
二、思路二 优化
1.想法
不拼接字符串 没获取一个字符串就直接比对
2.代码
#include<iostream>
#include <cstring>
#include <string.h>
#include<string>
using namespace std;
int main() {
int l, r, count = 0;
cin >> l >> r;
for (int i = l; i <= r; i++)
{
string s1 = to_string(i);
char b[10];
strcpy_s(b, s1.c_str());//在洛谷上操作时需要删去_s否则无法通过 原因暂时未知
for (int j = 0; j < strlen(b); j++)
{
if (b[j] == '2') {
count++;
}
}
}
cout << count;
return 0;
}
满分通过
二、继续优化 不用类型转换
注意while循环里面的变量不可以直接用for里面的i
//使用数字的方式 不进行类型转换
#include<iostream>
using namespace std;
int main() {
int l, r, count = 0;
cin >> l >> r;
for (int i = l; i <= r; i++)
{
int y = i;
while (y != 0) //原来是这里的错误 不能改变i的值因为这是上一个循环的值
{
int a = y % 10;
if (a == 2)
{
count++;
}
y = y / 10;
}
}
cout << count;
return 0;
}
总结
洛谷的代码运行环境为linux 类型转换容易出现很多异常 u
尽量避免使用类型转换或者是强制转换