题解 | #坐标移动#
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
#include <iostream> using namespace std; #include<string> #include<cmath> int getNum(string str) { int num = 0; for (int i = str.size() - 1, j = 0; i >= 1 ; i--, j++) { if ('0' <= str[i] && str[i] <= '9' ) { num = num + (str[i] - '0') * (pow(10, j)); } else { return -1; } } return num; } int main() { string str; int x = 0, y = 0; while (getline(cin, str, ';')) { switch (str[0]) { case 'A': { if (getNum(str) != -1) { x = x - getNum(str); } break; } case 'D': { if (getNum(str) != -1) { x = x + getNum(str); } break; } case 'W': { if (getNum(str) != -1) { y = y + getNum(str); } break; } case 'S': { if (getNum(str) != -1) { y = y - getNum(str); } break; } default: { break; } } } cout << x << "," << y << endl; }
使用 while (getline(cin, str, ';')) 这个语句读取以分号为结尾的字符串很好用,再简单写一个带报错的十进制字符串转int的函数就可以了
华为机试刷题记录 文章被收录于专栏
记录一下手打代码的解题思路方便复习