牛客華為機試-HJ17
–坐標移動–
//原題描述:

`
//c++實作坐標移動:
//題目:坐標移動(華為機試)
//作者:Micheal_Shen
//時間:2021-04-27
#include<bits/stdc++.h>
using namespace std;
/*移動位置*/
void action(string &str,pair<int,int> &location){
string temp(str.begin()+1,str.end());
char character = str[0];
int distance = stoi(temp);
if(character == 'A') location.first -= distance;
else if(character == 'D') location.first += distance;
else if(character == 'W') location.second += distance;
else if(character == 'S') location.second -= distance;
return;
}
/*判斷是否有效字串*/
bool isvalid(string &str){
bool res = false;
if(str.size() > 3||str.size() <= 1) return res;
if(str[0] == 'A'||str[0] == 'W'||str[0] == 'D'||str[0] == 'S'){
for(int i = 1; i < str.size(); ++i){
if(str[i]<'0'||str[i]>'9') return res;
}
res = true;
}
return res;
}
int main(){
string str = "";
pair<int,int> location{0,0};//記錄最終位置坐標
while(getline(cin,str,';')){//';'作為一次可能移動記錄
if(isvalid(str)) action(str,location);//判斷字串是否有效
else continue;//無效則繼續讀取
}
cout << location.first << ',' << location.second << endl;
return 0;
}
//作者:Micheal_Shen
//坐標:Nan Jing, China
//小伙伴們一起加油,沖鴨!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/280985.html
標籤:其他
