这道题最大难度在于面朝北,向右转朝向哪,再向右转朝向哪???
思路:周期,T=4,一直左转4次等于0,左转一次和右转一次抵消;
实现:定义“NESW”表示右转t次的方向,0<=t<4;右转direc+1,左转direc-1;然后通过周期4将direc转换到[0,4)。
(direc % 4 + 4) % 4,direc可能是负数,-5%4=-1,-1+4=3;
import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner scanner = new Scanner(System.in); String direction = "NESW"; while (scanner.hasNext()) { int n = scanner.nextInt(); String s = scanner.next(); int direc = 0; for(int i = 0; i < n; i++){ if(s.charAt(i) == 'R'){ direc++; }else{ direc--; } } direc = (direc % 4 + 4) % 4; System.out.println(direction.charAt(direc)); } } }