PAT 1118 如需挪车请致电

1118 如需挪车请致电 - PAT (Basic Level) Practice (中文) (pintia.cn)

我刚开始是这样写的:

js 复制代码
#include<bits/stdc++.h>
using namespace std;
map<string, int> m = { {"ling",0},{"yi",1},{"er",2},{"san",3},{"si",4},{"wu",5},{"liu",6},{"qi",7},{"ba",8},{"jiu",9} };

int main()
{
    int n = 11;
    string s;
    for (int i = 0; i < n; i++)
    {
        cin >> s;

        if (s.size() == 1)cout << s;
        else if (s[0] == 's' && s[1] == 'q')cout << sqrt(stoi(s.substr(4)));
        else if (m.count(s))cout << m[s];
        else
        {
            if (s[1] == '+')
            { 
                cout << s[0] - '0' + s[2] - '0';
            }
            else if (s[1] == '-')
            {
                cout << s[0] - '0' - s[2] - '0';
            }
            else if (s[1] == '*')
            {
                cout << s[0] - '0' * s[2] - '0';
            }
            else if (s[1] == '/')
            {
                cout << s[0] - '0' / s[2] - '0';
            }
            else if (s[1] == '%')
            {
                cout << s[0] - '0' % s[2] - '0';
            }
            else if (s[1] == '^')
            {
                cout << pow(s[0] - '0', s[2] - '0');
            }
        }
    }


    return 0;
}

但是这样会出现,因为题目说了运算数是1-9999的数字,不一定是一位数,如果像这样写死的话只能计算一位数字的运算。

要改成下面这样的

js 复制代码
#include <iostream>
#include <map>
#include <cmath>
#include <string>
using namespace std;
string s, c;
map<string,int> A = {{"ling", 0}, {"yi", 1}, {"er", 2}, {"san", 3}, {"si", 4}, {"wu", 5}, {"liu", 6}, {"qi", 7}, {"ba", 8}, {"jiu", 9}};
int main() {
    for (int I = 0; I < 11; I++) {
        cin >> s;
        if (s.size() == 1) cout << s;
        else if (s[0] == 's' && s[1] == 'q') cout << sqrt(stoi(s.substr(4)));
        else if (A.count(s)) cout << A[s];
        else {
            int a = 0, b = 0, i = 0;
            while(i < s.size() && isdigit(s[i])) a = a * 10 + s[i++] - '0';
            c = s[i++];
            while(i < s.size()) b = b * 10 + s[i++] - '0';
            if (c == "+") cout << a + b;
            else if (c == "-") cout << a - b;
            else if (c == "*") cout << a * b;
            else if (c == "/") cout << a / b;
            else if (c == "%") cout << a % b;
            else cout << pow(a, b);
        }
    }
    return 0;
}
相关推荐
复杂网络3 分钟前
多个 Claude Code 与多个 Codex 协同工作:设计与实现方案
算法
HjhIron16 小时前
面试常客:字符串算法从入门到进阶
算法·面试
吴佳浩17 小时前
DeepSeek DSpark:Confidence-Scheduled Speculative Decoding 技术解析
人工智能·算法·deepseek
触底反弹18 小时前
🧠 搞懂 Token,才算真正入门大模型——从分词原理到 Embedding 语义实战
javascript·人工智能·算法
vivo互联网技术1 天前
ICLR 2026 | 基于后验采样的图像恢复方法LearnIR:人脸去阴影、去雾
人工智能·算法·aigc
浮生望1 天前
JS字符串与回文算法:从包装类到双指针的面试进阶之路
javascript·算法
黄敬峰1 天前
面试必刷:从JS底层包装类到双指针,彻底搞懂字符串与回文算法
算法
地平线开发者1 天前
J6B vio scenario sample
算法
BothSavage2 天前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法