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;
}
相关推荐
√尖尖角↑2 小时前
力扣——【1991. 找到数组的中间位置】
算法·蓝桥杯
Allen Wurlitzer2 小时前
算法刷题记录——LeetCode篇(1.8) [第71~80题](持续更新)
算法·leetcode·职场和发展
百锦再3 小时前
五种常用的web加密算法
前端·算法·前端框架·web·加密·机密
碳基学AI4 小时前
北京大学DeepSeek内部研讨系列:AI在新媒体运营中的应用与挑战|122页PPT下载方法
大数据·人工智能·python·算法·ai·新媒体运营·产品运营
独家回忆3645 小时前
每日算法-250410
算法
袖清暮雨5 小时前
Python刷题笔记
笔记·python·算法
风掣长空6 小时前
八大排序——c++版
数据结构·算法·排序算法
流星白龙7 小时前
【C++算法】50.分治_归并_翻转对
c++·算法
Java致死8 小时前
费马小定理
算法·费马小定理
不吃元西8 小时前
leetcode 74. 搜索二维矩阵
算法·leetcode·矩阵