题解 | #坐标移动#

坐标移动

https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29

#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main() {
    string str;
    getline(cin, str);
    istringstream iss(str);
    string token="";
    vector<string> coordinates;
    //将所有的输入组成一个数组
    while (getline(iss, token, ';')) {
            coordinates.push_back(token);
    }
    int x = 0, y = 0;
    int number=0;
    for (string coordinate : coordinates) 
	{
	  //只选择合法的三种情况
	  //1.有三位,三位都是有效字符
        if ((coordinate.size() == 3) && isdigit(coordinate[1]) && isdigit(coordinate[2])) {
            number = (coordinate[1] - '0') * 10 + (coordinate[2] - '0');
        }
        //2.只有两位,且都是有效字符
        if ((coordinate.size() == 2) && isdigit(coordinate[1])) {
            number = coordinate[1] - '0';
        }
	  //3.只有1位
        if (coordinate.size() == 1)
            number = 0;
        //左移
        if (coordinate[0] == 'A') {
            x -= number;
        }
        //右移
        else if (coordinate[0] == 'D') {
            x += number;
        }
        //上移
        else if (coordinate[0] == 'W') {
            y += number;
        }
        //下移
        else if (coordinate[0] == 'S') {
            y -= number;
        }
    }
    cout << x << "," << y << endl;
    return 0;
}

全部评论

相关推荐

野猪不是猪🐗:这种直接口头上答应,骗面试,面完了直接拉黑,相当于给自己攒面经了(
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务