华为机试HJ17

牛客华为机试-HJ17

–坐标移动–

//原题描述:

华为机试HJ17_第1张图片
`华为机试HJ17_第2张图片

//c++实现坐标移动:

//题目:坐标移动(华为机试)
//作者:Micheal_Shen
//时间:2021-04-27
#include
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
//小伙伴们一起加油,冲鸭!

你可能感兴趣的:(华为机试,字符串)