每日一道算法题 坐标移动

题目

坐标移动_牛客题霸_牛客网 (nowcoder.com)

c语言

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
//#include <string.h>

int main()
{
	char str[10001] = { 0 };
	//strcpy(str, "A10;S20;W10;D30;X;A1A;B10A11;;A10;");
	scanf("%s", str);
	char *p = str;
	int x = 0;
	int y = 0;
	int step = 0;
	char d = 0;  //方向
	while (*p != '\0')
	{
		//匹配方向
		if (!d)
		{
			if (*p== 'A' || *p == 'D' || *p == 'W' || *p == 'S')
			{
				d = *p;
				*p++;
				continue;
			}
			else
			{
				while (*p != '\0' && *p != ';')
				{
					*p++;
				}
			}
		}
		//匹配到方向
		if (d)
		{
			if (*p >= '0' && *p <= '9')
			{
				step *= 10;
				step += (*p - '0');
			}
			else if (*p == ';')
			{
				if (d == 'A') x -= step;

				else if (d == 'D') x += step;

				else if (d == 'W') y += step;

				else if (d == 'S') y -= step;

				step = 0;
				d = 0;
			}
			else
			{
				step = 0;
				d = 0;
			}
		}
		p++;

	}
	printf("%d,%d", x, y);
	return 0;
}

c++

#include <iostream>
#include <string>
#include <sstream>
#include <regex>
using namespace std;

int main()
{
	//"A10;S20;W10;D30;X;A1A;B10A11;;A10;"
	string s, c;
	//getline(cin, s);
	//cout<<s<<endl;
	while (getline(cin, s))
	{
		stringstream ss(s);
		pair<int, int> x_y(0, 0);
		while (getline(ss, c, ';'))
		{
			//cout << c << endl;
			if (c.empty()) continue;
			string _ = c.substr(1);
			//cout << _ << endl;
			if (regex_match(_, regex("[0-9]*")))
			{
				switch (c[0])
				{
				case 'A':x_y.first -= stoi(_); break;
				case 'D':x_y.first += stoi(_); break;
				case 'W':x_y.second += stoi(_); break;
				case 'S':x_y.second -= stoi(_); break;
				default:break;

				}

			}

		}
		cout << x_y.first << ',' << x_y.second;
	}
	return 0;
}

python

s=input()
s=s.split(';')
x=y=0

for _ in s:
    if not _:
        continue
    try:
        if _[0]=='A':
            x-=int(_[1:])
        elif _[0]=='D':
            x+=int(_[1:])
        elif _[0]=='W':
            y+=int(_[1:])
        elif _[0]=='S':
            y-=int(_[1:])
        else:
            continue
    except:
        continue
print(f"{x},{y}")

  • 20
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值