牛客网_华为机试_017_坐标移动

来源:互联网 发布:美国最新经济数据今晚 编辑:程序博客网 时间:2024/06/12 07:18

题目描述

开发一个坐标计算工具, A表示向左移动,D表示向右移动,W表示向上移动,S表示向下移动。从(0,0)点开始移动,从输入字符串里面读取一些坐标,并将最终输入结果输出到输出文件里面。

 

输入:

 

合法坐标为A(或者D或者W或者S) + 数字(两位以内)

 

坐标之间以;分隔。

 

非法坐标点需要进行丢弃。如AA10;  A1A;  $%$;  YAD; 等。

 

下面是一个简单的例子 如:

 

A10;S20;W10;D30;X;A1A;B10A11;;A10;

 

处理过程:

 

起点(0,0)

 

+   A10   =  (-10,0)

 

+   S20   =  (-10,-20)

 

+   W10  =  (-10,-10)

 

+   D30  =  (20,-10)

 

+   x    =  无效

 

+   A1A   =  无效

 

+   B10A11   =  无效

 

+  一个空 不影响

 

+   A10  =  (10,-10)

 

 

 

结果 (10, -10)


输入描述:

一行字符串

输出描述:

最终坐标,以,分隔

示例1

输入

A10;S20;W10;D30;X;A1A;B10A11;;A10;

输出

10,-10

题目地址:https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29?tpId=37&tqId=21240&tPage=1&rp=&ru=/ta/huawei&qru=/ta/huawei/question-ranking

思路一:利用find找到第一个;的位置,提取;前的字符串进行分析,然后保留剩下的再次循环

#include <string>#include <iostream>using namespace std;bool move(string order, int &x, int &y){string num = "";    //取数字部分for (int i = 1; i < order.size(); i++) {        //判断数字是否有效if (order[i] < '0' || order[i] >'9')return false;num.append(1, order[i]);}    //判断数字是否有效if (num.empty())return false;int step = stoi(num);    //判断、执行移动指令switch (order[0]) {case 'W':y += step;break;case 'S':y -= step;break;case 'A':x -= step;break;case 'D':x += step;break;default:return false;}return true;}int main(){string inputStr = "";while (getline(cin, inputStr)) {int x = 0;int y = 0;        //第一个';’的位置int index = inputStr.find(";");while (index != string::npos) {string temp = inputStr.substr(0, index);move(temp, x, y);inputStr = inputStr.substr(index + 1);index = inputStr.find(";");}cout << x << "," << y << endl;}return 0;}


原创粉丝点击