题解 | #坐标移动#
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
#include<iostream> #include<string> #include<cmath> using namespace std; int main() { string s; cin >> s; //用s接收输入的字符串 int n = s.size(); string move; //move存储坐标 int x = 0, y = 0; //x和y分别为两个坐标值 char direction = 'W'; //坐标中的方向 while (1) { int e = 0; //判断坐标中字母后是否全为数字 int p = 0; //用于标记分号的位置 for (int i = 0; i < n; i++) { if (s[i] == ';') { p = i; break; } } move = s.substr(0,p); //根据分号的位置将坐标字符串分割出来 for (int k = 1; k < move.size(); k++) { if ((move[k] < '0') || (move[k] > '9')) { e++; } } if (e != 0) { //判断坐标字符串中第二个字符开始是否全为数字,否则不合法 s = s.substr(p + 1, n - 1 - p); n = s.size(); continue; } int num = 0; //根据move计算具体的两个坐标值 for (int j = 1; j < move.size(); j++) { num = num + (move[j] - 48) * pow(10, move.size() - j - 1); } direction = move[0]; if (direction == 'A') { x = x - num; } else if (direction == 'D') { x = x + num; } else if (direction == 'W') { y = y + num; } else if (direction == 'S') { y = y - num; } if (p == n - 1) { break; } s = s.substr(p + 1, n - 1 - p);//更新整个字符串,将处理过的部分去掉 n = s.size(); } cout << x << "," << y << endl; return 0; }#初学者代码#