HJ17 题解 | #坐标移动#
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
#include<iostream>
#include<string>
using namespace std;
bool isValid(string s, char& op, int& op_xy); //判定指令是否合法
int moveCoord(string s, int& x, int& y); //移动坐标
bool isValid(string s, char& op, int& op_xy) {
int len = s.length();
if (len <= 1) { //指令为空或只有一个字符,不合法
return false;
}
op = s[0];
//指令第一个字符不是A,D,W,S之一,不合法
if (op != 'A' && op != 'D' && op != 'W' && op != 'S') {
return false;
}
string s_xy = s.substr(1, len);
for (int i = 0; i < len - 1;
i++) { //指令坐标字段的字符不是数字,不合法
if (s_xy[i] < '0' || s_xy[i] > '9') {
return false;
}
}
op_xy = stoi(s_xy); //坐标字段转十进制数字
if (op_xy > 99 || op_xy < 0) { //坐标值不是两位数以内,不合法
return false;
}
return true;
}
int moveCoord(string s, int& x, int& y) {
char op = '0';
int op_xy = 0;
bool tag = isValid(s, op,
op_xy); //检查指令合法性,若合法,则获取移动方向op和距离op_xy
if (tag) {
switch (op) {
case 'A':
x -= op_xy;
break;
case 'D':
x += op_xy;
break;
case 'W':
y += op_xy;
break;
case 'S':
y -= op_xy;
break;
}
}
return 0;
}
int main() {
int x = 0, y = 0;
string str;
getline(cin, str);
int len = str.length();
int i = 0;
while (i < len) {
int j = i, k = 0;
while (str[j] != ';' && j < len) {
k++;
j++;
}
string str_sub = str.substr(i, k); //双指针分割字符串
moveCoord(str_sub, x, y); // 移动坐标
i = j + 1;
}
cout << x << "," << y;
return 0;
}
华为机试刷题实录 文章被收录于专栏
记录一下本科应届生(我自己)刷华为机试题的过程

