题解 | 坐标移动

坐标移动

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

#include <iostream>
using namespace std;

int x = 0;
int y = 0;

inline bool isMove(char c) {
    return c == 'A' || c == 'W' || c == 'S' || c == 'D';
}

inline bool isNumber(char c) {
    return c >= '0' && c <= '9';
}

void executeCommand(const string& command) {
    int n = command.size();
    if (n < 2 || !isMove(command[0])) {
        return;
    }
    char c;
    int step = 0;
    for (int i = 1; i < n; i++) {
        c = command[i];
        if (!isNumber(c) || (i == 1 && c == '0')) {
            return;
        }
        step = step * 10 + c - '0';
    }

    switch (command[0]) {
        case 'A':
            x -= step;
            break;
        case 'W':
            y += step;
            break;
        case 'S':
            y -= step;
            break;
        case 'D':
            x += step;
            break;
    }
    // cout << x << "," << y << endl;
}

int main(int, char**) {
    string s;
    cin >> s;
    int n = s.size();
    int i = 0;
    while (i < n) {
        auto pos = s.find(';', i);
        if (pos == string::npos) {
            break;
        }
        int length = pos - i;
        string command = s.substr(i, length);
        // cout << command << endl;
        executeCommand(command);
        i = pos + 1;
    }
    cout << x << "," << y << endl;
}

全部评论

相关推荐

04-14 20:10
已编辑
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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