21天刷题计划之10.2—牛牛偶像养成记(Java语言描述)

题目描述:

牛牛去犇犇老师家补课,出门的时候面向北方,但是现在他迷路了。虽然他手里有一张地图,但是他需要知道自己面向哪个方向,请你帮帮他。

输入描述:

每个输入包含一个测试用例。
每个测试用例的第一行包含一个正整数,表示转方向的次数N(N<=1000)。
接下来的一行包含一个长度为N的字符串,由L和R组成,L表示向左转,R表示向右转。

输出描述:

输出牛牛最后面向的方向,N表示北,S表示南,E表示东,W表示西。

示例1

输入
3
LRR

输出
E

分析:

由于最终输出只有四个方向,所以可以建立一个字符串数组String dir[]存储四个位置的信息,根据东南西北的相对位置,他们在数组中的相对位置分布为:

W N E S

W的左边为S,S的右边为W。循环数组。
初始指针pos = 1;
然后遍历输入的移动方向字符串,若是‘L’,则执行pos–操作,若是‘R’,则执行pos++操作,接着需要判别指针的位置,若pos<0,则将pos置为3,若pos>3,则将pos置为0;

代码实现如下:

import java.util.Scanner;

public class Main {

	public static void main(String[] args) throws Exception {
		
		Scanner scan = new Scanner(System.in);
		while(scan.hasNext()){
			int times = scan.nextInt();
			String str = scan.next();
			System.out.println(faceDirection(times,str));
		}
		scan.close();
	}

	public static String faceDirection(int times, String str) throws Exception {
		
		if(times!=str.length()){
			throw new Exception("输入有误,请检查后重新输入!");
		}
		String[] dir = new String[4];
		int pos = 1;
		dir[0] = "W";//分别将四个方位按照相对位置存入数组。
		dir[1] = "N";
		dir[2] = "E";
		dir[3] = "S";
		
		for(int i = 0; i<str.length();i++){
			if(str.charAt(i)=='L'){
				pos--;
			}
			if(str.charAt(i)=='R'){
				pos++;
			}
			
			if(pos<0){
				pos = 3;
			}
			if(pos>3){
				pos = 0;
			}
		}
		return dir[pos];
	}

}

猜你喜欢

转载自blog.csdn.net/justlikeu777/article/details/83095192