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;
}
相关推荐
倒头就睡的小比特5 天前
算法竞赛C++常用的STL
c++·算法
小羊没烦恼!5 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
猎头南楼5 天前
知识社区推荐系统实践:新用户冷启动与长短期兴趣建模的挑战 资深推荐算法工程师
人工智能·深度学习·算法·机器学习
旖旎夜光5 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
wzdark5 天前
大规模并行计算中的负载均衡算法研究4
算法
Because_of_Her15 天前
并查集-听课笔记
笔记·算法·并查集
码流子5 天前
高速公路安全监测实践:碰撞监测预警+物联网底座,从感知到处置的闭环
大数据·人工智能·物联网·算法·架构
another heaven5 天前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法
wzdark5 天前
从算法设计模式看编程思维的抽象能力4
算法
2601_962218615 天前
万象生鲜系统称重自动多退少补算法解决生鲜非标品痛点
大数据·数据库·人工智能·python·算法