题解 | #坐标移动#
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
#include <cstddef> #include <cstdlib> #include <cstring> #include <iostream> #include <string> using namespace std; bool is_number(const string& str) { for (auto& c : str) { if (!('0' <= c && c <= '9')) { return false; } } return !str.empty(); } bool move_corr(const char dir, const std::string& step_str, int* x, int* y) { if (!is_number(step_str)) { return false; } const int step = atoi(step_str.c_str()); if (step <= 0) { return false; } switch (dir) { case 'A': { *x -= step; break; } case 'D': { *x += step; break; } case 'W': { *y += step; break; } case 'S': { *y -= step; break; } default: { return false; } } return true; } int main() { string text; getline(cin, text); int x = 0, y = 0; string::size_type pos = 0; while ((pos = text.find(';')) != string::npos) { auto token = text.substr(0, pos); text.erase(0, pos + 1); if (token.length() >= 2) { const char dir = token[0]; const string step_str = token.substr(1); move_corr(dir, step_str, &x, &y); } } cout << x << "," << y << endl; }