两道笔试题(笔记)

多多君接到了一个给活动商品编号的任务:每次可选的商品编号区间是[L,R]。由于活动的日期定在05月20号,多多君认为包含5,20和520的编号是有特殊含义,准备保留给对应的商品。例如:618520,其中包含了520,是一个特殊编号;而12368就是一个普通编号。多多君想知道,在可选的商品编号区间内,有多少符合上面要求的特殊编号。

输入描述 第一行,1个整数T,表示每次可选的编码区间。( 1 <=T<= 1,000 ) 接下来T行,每行2个整数:L和R,表示编码可选的区间(闭区间,即包括L和R)。( 1<=L<=R<= 1,000,000 )

输出描述 共T行,每行3个整数,分别表示对应区间里的5、20和520的编号数量

#include <iostream>
#include <string>
#include <cstring>

using namespace std;

const int mxn = 1000000;
int pre5[mxn + 1], pre20[mxn + 1], pre520[mxn + 1];

int main() {
    memset(pre5, 0, sizeof(pre5));
    memset(pre20, 0, sizeof(pre20));
    memset(pre520, 0, sizeof(pre520));

    for(int i = 1; i <= mxn; i++) {
        pre5[i] = pre5[i - 1];
        pre20[i] = pre20[i - 1];
        pre520[i] = pre520[i - 1];
        if(to_string(i).find('5') != string::npos) {
            pre5[i]++;
        }
        if(to_string(i).find("20") != string::npos) {
            pre20[i]++;
        }
        if(to_string(i).find("520") != string::npos) {
            pre520[i]++;
        }
    }

    int T;
    cin >> T;
    while(T--) {
        int L, R;
        cin >> L >> R;
        cout << pre5[R] - pre5[L-1] << " ";
        cout << pre20[R] - pre20[L-1] << " ";
        cout << pre520[R] - pre520[L-1] << endl;
    }

    return 0;
}
#include <iostream>
#include <string>

using namespace std;

int main() {
    int T;
    cin >> T;

    while (T--) {
        // 读取区间 L 和 R
        int L, R;
        cin >> L >> R;

        // 统计特殊编号数目
        int cnt_5 = 0, cnt_20 = 0, cnt_520 = 0;
        for (int i = L; i <= R; i++) {
            string s = to_string(i);
            if (s.find('5') != string::npos) {
                cnt_5++;
            }
            if (s.find("20") != string::npos) {
                cnt_20++;
            }
            if (s.find("520") != string::npos) {
                cnt_520++;
            }
        }

        // 输出结果
        cout << cnt_5 << " " << cnt_20 << " " << cnt_520 << endl;
    }

    return 0;
}

小美有两个数字,其中第一个数字是任意的正整数,第二个数字是一位仅可能为0到9间的整数。小美希望能将第二个插入第一个数字中,以得到最大的数字。具体可参见输入输出样例。

输入描述

单个测试用例包含T组数据

第一行一个数字表示T

对于每一组数据,包含一行有2个空格隔开的整数,表示任意正整数a和待插入的数字b。

1≤T≤10, 1≤a≤1050000, 0≤b≤9

输出描述

对于每组数据,输出一行,包括一个整数,得到的最大整数。

#include <iostream>
#include <string>
using namespace std;

int main() {
    int T;
    cin >> T;

    while (T--) {
        int a, b;
        cin >> a >> b;

        string s = to_string(a);
        bool found = false; // 标记是否插入 b
        for (int i = 0; i < s.size(); i++) {
            if (s[i] - '0' < b) {
                s.insert(i, to_string(b));
                found = true;
                break;
            }
        }

        if (!found) { // 如果所有数字都大于等于 b,则在末尾插入 b
            s.push_back(b + '0');
        }

        cout << s << endl;
    }

    return 0;
}

在 C++ 中,我们可以使用 to_string() 将整数转化为字符串,然后再通过string的find函数或者insert函数

猜你喜欢

转载自blog.csdn.net/hbzdsXCV/article/details/130713160