题解 | #坐标移动#
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
#include <iostream>
#include <string>
#include <cctype>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;
class Point {
public:
Point(int x, int y)
: _x(x), _y(y)
{}
void print() {
cout << _x << "," << _y << endl;
}
Point remove_function(char ch, int num) {
switch (ch) {
case 'A':
return Point(_x - num, _y);
case 'S':
return Point(_x, _y - num);
case 'W':
return Point(_x, _y + num);
case 'D':
return Point(_x + num, _y);
default:
return *this; // 返回当前对象
}
}
private:
int _x;
int _y;
};
int main(int argc, char* argv[]) {
Point p(0, 0);
Point p1(0, 0);
vector<string> vec;
char ch;
int num;
string str;
/* while (getline(cin, str, ';')) {
vec.push_back(str);
}*/
getline(cin, str);
for (int i = 0; i < str.size(); i = i + 1)
{
string temp;
while (str[i] != ';')
{
temp.push_back(str[i]);
i = i + 1;
}
vec.push_back(temp);
}
/* for (const auto& elem : vec) {
cout << elem << " ";
}
cout << endl;*/
for (const auto& cmd : vec) {
if (cmd.length() == 2 && isalpha(cmd[0]) && isdigit(cmd[1])) {
ch = cmd[0];
num = cmd[1] - '0'; // 假设数字只有一位
/*cout << "数字只有一位num =" << num;*/
p1 = p.remove_function(ch, num);
p = p1; // 更新当前点
}
else if (cmd.length() == 3 && isalpha(cmd[0]) && isdigit(cmd[1]) && isdigit(cmd[2])) {
ch = cmd[0];
num = (cmd[1] - '0' )* 10 + cmd[2] - '0'; // 假设数字有两位
/* cout << "数字有两位num =" << num << endl;*/
p1 = p.remove_function(ch, num);
p = p1; // 更新当前点
}
}
p1.print();
return 0;
}
