题解 | #坐标移动#

坐标移动

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

本题总体上来说不难,主要在字符串切割和边界条件判断上,对getline不太了解可以去查了一下。

#include <iostream>
using namespace std;
struct Point {
    int x;
    int y;
};

int str2int(string str) {
    for (auto c : str) {
        if ((c < '0' || c > '9')) {
            return 0;
        }
    }
    return stoi(str);
}

void calculatePointXY(string& str, Point& point) {
    int num = str2int(str.substr(1));
    switch (str[0]) {
        case 'A':
            point.x -= num;
            break;
        case 'D':
            point.x += num;
            break;
        case 'W':
            point.y += num;
            break;
        case 'S':
            point.y -= num;
            break;
        default:
            break;
    };
}

int main() {
    string str;
    Point point{0, 0};
    while (getline(cin, str, ';')) {
        if (str.length() >= 2 && str.length() <= 3) {
            calculatePointXY(str, point);
        }
    }
    printf("%d,%d", point.x, point.y);
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

看网上风评也太差了
投递万得信息等公司8个岗位 >
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务