题解 | 坐标移动

坐标移动

https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int x;
int y;

bool check(string str) {
    int len = str.length();
    if (len < 2 || len > 3)    return false;
    char op = str[0];
    if (op == 'A' || op == 'S' || op == 'D' || op == 'W') {
        if (len == 2) {
            if (str[1] >= '0' && str[1] <= '9')  return true;
            else return false;
        } else {
            if (str[1] >= '0' && str[2] >= '0' && str[1] <= '9' && str[2] <= '9')
                return true;
            else    return false;
        }
    }
    return false;
}

void operate(char op, int n) {
    switch (op) {
        case 'A':
            x -= n;
            break;
        case 'D':
            x += n;
            break;
        case 'W':
            y += n;
            break;
        case 'S':
            y -= n;
            break;
        default:
            break;
    }

}

int main() {
    string s;
    cin >> s;
    for (auto& elem : s)
        if (elem == ';')
            elem = ' ';
    istringstream iss(s);
    string order;
    while (iss >> order) {
        if (check(order)) {
            char op = order[0];
            string num(order.begin() + 1, order.end());
            operate(op, stoi(num));
        }
    }

    cout << x << ',' << y << endl;
    return 0;
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务