【codingame】【C语言】Clash of Code——求字符串表示的移动路径并输出

97 阅读1分钟

根据以下例子写出对应代码: image.png

算法思想:将输入字符串保存到字符串数组中,当当前字符为‘-’时,表示移动1 block,用此count变量保存block的值;当字符为‘R’时,输出“Turn Right”;当字符为‘L’,输出“Turn Left”,最后输出“You ve reached your destination”表示到达目的地,结束程序

#include <stdio.h>
#include <string.h>

int main() {
    char s[100];
    int k = 0;
    fgets(s, 100, stdin);

    for (int i = 0; i < strlen(s); i++) {
        if (s[i] == '-') {
            k += 1;
        } else {
            if (k) printf("Go %d blocks Forward\n", k);
            k = 0;
            if (s[i] == 'R') printf("Turn Right\n");
            else if(s[i] == 'L')printf("Turn Left\n");
        }
    }
    printf("You've reached your destination\n");

    return 0;
}

示例1:

----R----L--
Go 4 blocks Forward
Turn Right
Go 4 blocks Forward
Turn Left
Go 2 blocks Forward
You've reached your destination

示例2:

----RL--L
Go 4 blocks Forward
Turn Right
Turn Left
Go 2 blocks Forward
Turn Left
You've reached your destination

示例3:

RLRRRLL
Turn Right
Turn Left
Turn Right
Turn Right
Turn Right
Turn Left
Turn Left
You've reached your destination