题解 | #坐标移动#

坐标移动

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

#include <iostream>
#include <string>
using namespace std;

//点类
class Point {
  private:
    int x;
    int y;

  public:
    //无参构造函数
    Point() {
        this->x = 0;
        this->y = 0;
        return;
    }

    //构造函数
    Point(const int x, const int y) {
        this->x = x;
        this->y = y;
        return;
    }

    //析构函数
    ~Point() {}

    //向左移动
    void moveleft(const int x) {
        this->x -= x;
        return;
    }

    //向右移动
    void moveright(const int x) {
        this->x += x;
        return;
    }

    //向上移动
    void moveup(const int y) {
        this->y += y;
        return;
    }

    //向下移动
    void movedown(const int y) {
        this->y -= y;
        return;
    }

    //移动
    void move(const char ch, const int n) {

        //如果方向正确,移动;否则不移动
        switch (ch) {
            case 'A':
                this->moveleft(n);
                break;
            case 'D':
                this->moveright(n);
                break;
            case 'W':
                this->moveup(n);
                break;
            case 'S':
                this->movedown(n);
                break;
            default:
                break;
        }
        return;
    }

    //处理坐标点(移动或丢弃)
    void disposs(const string s) {
        char ch = 0;
        int n = 0;

        //提取方向
        ch = s[0];

        //如果方向正确
        if ((ch == 'A') || (ch == 'D') || (ch == 'W') || (ch == 'S'))

            //如果后续是数字
            if (('0' <= s[1]) && (s[1] <= '9')) {

                //如果后续是分号,坐标点结束,坐标正确,移动
                if (s[2] == ';') {
                    n = s[1] - '0';
                    this->move(ch, n);
                    return;
                }

                //如果后续是数字
                if (('0' <= s[2]) && (s[2] <= '9')) {

                    //由于数字最多两位,直接转化数字
                    n = s[2] - '0' + (s[1] - '0') * 10;

                    //如果后续是分号,移动
                    if (s[3] == ';') {
                        this->move(ch, n);
                        return;
                    }
                }
            }
        return;
    }

    //处理输入数据
    void process(const string s) {
        int m = -1;
        int n = 0;
        for (int i = 0; i < s.size(); i++) {
            //截断坐标点,进一步处理
            if (s[i] == ';') {
                n = i;
                string s1 = s.substr(m + 1, n - m);
                this->disposs(s1);
                m = n;
            }
        }
        return;
    }

    //输出
    void print(void) {
        cout << this->x << ',' << this->y << endl;
        return;
    }
};

int main() {
    string s;
    s.clear();
    while (getline(cin, s)) { // 注意 while 处理多个 case
        Point p;
        p.process(s);
        p.print();
        s.clear();
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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