题解 | 坐标移动
坐标移动
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")
