题解 | #坐标移动#
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
用字符指针减少拷贝的做法
#include <iostream>
#include <string>
using namespace std;
int StrToNum(const char* num) {
if (!num) {
return -1;
}
const char* p = num;
int res = 0;
while (*p && *p != ';' && *p >= '0' && *p <= '9') {
res = res * 10 + (*p - '0');
++p;
}
if (*p != ';') {
return -1;
}
return res;
}
void ParseAction(const char* begin, int* action_x, int* action_y) {
int steps = StrToNum(begin + 1);
if (steps <= 0) {
return;
}
switch (*begin) {
case 'A': *action_x -= steps; break;
case 'D': *action_x += steps; break;
case 'S': *action_y -= steps; break;
case 'W': *action_y += steps; break;
default: break;
}
}
void GetCoordinates(const std::string& actions, int* x, int* y) {
auto it = actions.begin();
while (it != actions.end()) {
ParseAction(&(*it), x, y);
while (*it && *it++ != ';')
;
}
}
int main() {
std::string in;
cin >> in;
int x = 0, y = 0;
GetCoordinates(in, &x, &y);
cout << x << ',' << y << '\n';
}
查看16道真题和解析