洛谷: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;
}

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章