题解 | #坐标移动#
坐标移动
https://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
typedef struct {
char direction;//0上,1下,2做,3右
long long step;
int offset;
}parse_out_t;
//只是转换正整数,错误则返回0
long long str2ll(char *str, int str_len)
{
long long ret = 0;
//检查是否是数值字符
int i = 0;
//printf("str_len:%d ", str_len);
for (i = 0; i < str_len; i++) {
if (str[i] <'0' || str[i] > '9') {
return 0;
}
//printf("%c ", str[i]);
}
for (i = 0; i < str_len; i++) {
int fac = pow(10, str_len-i-1);
ret += fac * (str[i]- '0');
//printf("fac:%d ", fac);
}
//printf("ret:%lld\n", ret);
return ret;
}
//返回0表示失败,返回>0表示字符串解析了几个字符
int parse(char *str, parse_out_t *out)
{
int ret = 0;
if (!str)
return 0;
memset(out, 0, sizeof(parse_out_t));
out->offset = 1;
switch (*str) {
case 'A':
case 'D':
case 'W':
case 'S':
out->direction = *str;
break;
default:
{
char * end = strchr(str, ';');
out->offset = end - str+1;
}
return 0;
}
char * end = strchr(str, ';');
if (!end) {
return 0;
}
out->offset = end - str+1;
if ((out->step = str2ll(str+1, out->offset-2)) == 0) {
//printf("2ll err ");
return 0;
}//A10;S20;W10;D30;X;A1A;B10A11;;A10;
return 1;
}
int main() {
char str[10001] = {0};
memset(str, 0, sizeof(str));
scanf("%s", str);
long long x = 0, y = 0;
//解析
char *p = str;
parse_out_t out;
while (*p != 0) {
if (parse(p, &out) != 0) {
switch (out.direction) {
case 'A':
x -= out.step;
break;
case 'D':
x += out.step;
break;
case 'W':
y += out.step;
break;
case 'S':
y -= out.step;
break;
}
}
//printf("offset:%d\n", out.offset);
p += out.offset;
}
printf("%lld,%lld", x, y);
return 0;
}
强撸灰飞烟灭
改BUG改了很久
没有考虑到坐标字符错误的情况,例如这种情况:B10A11;