题解 | #坐标移动#
坐标移动
http://www.nowcoder.com/practice/119bcca3befb405fbe58abe9c532eb29
#include<stdio.h>
#define IS_DIGIT(x) (((x) >= '0') && ((x) <= '9'))
int Str2Num(const char *str, int *num)
{
int n = 0;
for (; *str; str++) {
if (!IS_DIGIT(*str))
return -1;
n *= 10;
n += *str - '0';
}
*num = n;
return 0;
}
void Move(const char *cmd, int len, int *x, int *y)
{
int num;
if (len > 3 || len < 2)
return;
if (Str2Num(cmd + 1, &num) < 0)
return;
switch (cmd[0]) {
case 'W':
*y += num;
break;
case 'S':
*y -= num;
break;
case 'D':
*x += num;
break;
case 'A':
*x -= num;
break;
}
}
void Parse(char *str)
{
for (i = 0; str[i]; i++) {
if (str[i] != ';')
continue;
str[i] = 0;
Move(str, strlen(str), &x, &y);
str = str + i + 1;
i = -1;
}
printf("%d,%d\n", x, y);
}
int main()
{
while (gets(buf) != NULL)
Parse(buf);
return 0;
}
#define IS_DIGIT(x) (((x) >= '0') && ((x) <= '9'))
int Str2Num(const char *str, int *num)
{
int n = 0;
for (; *str; str++) {
if (!IS_DIGIT(*str))
return -1;
n *= 10;
n += *str - '0';
}
*num = n;
return 0;
}
void Move(const char *cmd, int len, int *x, int *y)
{
int num;
if (len > 3 || len < 2)
return;
if (Str2Num(cmd + 1, &num) < 0)
return;
switch (cmd[0]) {
case 'W':
*y += num;
break;
case 'S':
*y -= num;
break;
case 'D':
*x += num;
break;
case 'A':
*x -= num;
break;
}
}
void Parse(char *str)
{
int i, x = 0, y = 0;
if (str[i] != ';')
continue;
str[i] = 0;
Move(str, strlen(str), &x, &y);
str = str + i + 1;
i = -1;
}
printf("%d,%d\n", x, y);
}
int main()
{
char buf[10001];
Parse(buf);
return 0;
}