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

在這裏插入圖片描述

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