洛谷:P1179 数字统计 C++三种写法总结
0、前言
以前刷力扣的时候用过atoi函数,但是好像这道题没必要吧……
今天刷洛谷的时候,看见一道数字统计,这么简单的题目还没做!天理难容啊,打开,我相信五分钟就敲完了,我打算改进代码,下面是几种方法,越来越好!
1、stringstream
以前的代码可以这么写,但是时间会慢一点,stringstream是简单,但是很耗时
#include <iostream>
#include <string>
#include <cstdlib>
#include <sstream>
using namespace std;
string int2str(int aNum)
{
stringstream res;
res << aNum;
string ans;
res >> ans;
return ans;
}
int char2int(char ch)
{
stringstream res;
res << ch;
int aNum;
res >> aNum;
return aNum;
}
int main()
{
int start, end;
int count = 0;
cin >> start >> end;
for (int i = start; i <= end; i++)
{
string stmp = int2str(i);
for (int idx = 0; idx < stmp.size(); idx++)
{
if (char2int(stmp[idx]) == 2)
count++;
}
}
cout << count << endl;
return 0;
}
这样可以通过
非常棒!
2、部分改进to_string()
好,那么既然string库有to_string
函数,那么为什么不用呢?
#include <iostream>
#include <string>
#include <cstdlib>
#include <sstream>
using namespace std;
int char2int(char ch)
{
stringstream res;
res << ch;
int aNum;
res >> aNum;
return aNum;
}
int main()
{
int start, end;
int count = 0;
cin >> start >> end;
for (int i = start; i <= end; i++)
{
string stmp = to_string(i);
for (int idx = 0; idx < stmp.size(); idx++)
{
if (char2int(stmp[idx]) == 2)
count++;
}
}
cout << count << endl;
return 0;
}
看图就知道,速度又快了一点!💪
直接判断不就行了😱
我可能有点晕,才发现用不着转化字符啊,直接判断字符不就完了?
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
int start, end;
int count = 0;
cin >> start >> end;
for (int i = start; i <= end; i++)
{
string stmp = to_string(i);
for (int idx = 0; idx < stmp.size(); idx++)
{
if (stmp[idx] == '2')
count++;
}
}
cout << count << endl;
return 0;
}
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 开发的设计和重构,为开发效率服务
· 从零开始开发一个 MCP Server!
· Ai满嘴顺口溜,想考研?浪费我几个小时
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想