题解 | #坐标移动#
坐标移动
http://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
比较笨比的方式,先根据 ‘ ; ’ 拿数据,然后传数据进行有效性判断。
#include "stdio.h"
#include "string.h"
typedef struct
{
int x;
int y;
}coordinate_t;
void move_dst(coordinate_t* position,char *str,int data_len)
{
if(data_len < 2 || data_len > 3)
return;
for(int i =1;i<data_len;i++)
{
if(*(str+i) < '0' || *(str+i) > '9')
return;
}
int res = (data_len == 2)?*(str + data_len-1)-'0':(*(str+data_len - 2 )-'0')*10 + *(str + data_len-1)-'0';
switch (*(str+0))
{
case 'A': position->x -= res;
break;
case 'W': position->y += res;
break;
case 'S': position->y -= res;
break;
case 'D': position->x += res;
break;
default:
break;
}
}
int main()
{
coordinate_t start = {0,0};
char operation[10001] = {0};
gets(operation);
int size = 0;
for(int i=0;i<strlen(operation);i++)
{
if(operation[i] != ';')
size++;
else
{
move_dst(&start,&operation[i-size],size);
size = 0;
}
}
printf("%d,%d",start.x,start.y);
return 0;
}