题解 | 坐标移动

坐标移动

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

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

struct Position
{
    int x = 0;
    int y = 0;

    void move_down(int step)
    {
        y -= step;
    }

    void move_left(int step)
    {
        x -= step;
    }

    void move_right(int step)
    {
        x += step;
    }

    void move_up(int step)
    {
        y += step;
    }

    void where_am_i()
    {
        cout << x << ',' << y << endl;
    }
};

int get_step(string str)
{
    string step_str;
    for (int i = 1; i < str.size(); i++) {
        if (str[i] == '0' && step_str.size() == 0) {
            continue;
        } else if (str[i] < '0' || str[i] > '9') {
            return -1;
        } else {
            step_str.push_back(str[i]);
        } 
    }
    // cout << step_str << endl;
    if (step_str.empty()) return 0;
    return stoi(step_str);
}

int main() {
    string input_str;
    struct Position man;
    // vector<string> cmds;
    while (getline(cin, input_str, ';')) {
        if (!input_str.empty() && (input_str[0] == 'A' || input_str[0] == 'D' || input_str[0] == 'W' ||      input_str[0] == 'S')) {
            int step;
            step = get_step(input_str);
            if (step <= 0 || step >= 100) continue;
            // cout << step << endl;
            switch (input_str[0]) {
            case 'A':
                man.move_left(step);
            break;
            case 'D':
                man.move_right(step);
            break;
            case 'W':
                man.move_up(step);
            break;
            case 'S':
                man.move_down(step);
            break;
            default:
            break;
            }
            // cout << input_str << endl;
            // cmds.push_back(input_str);
        }
        
    }
    man.where_am_i();
    
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

10-30 19:23
已编辑
山东大学(威海) C++
牛至超人:其实简历是不需要事无巨细的写的,让对方知道你有这段经历就行了,最重要的是面试的时候讲细讲明白
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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