题解 | #MP3光标位置#
MP3光标位置
https://www.nowcoder.com/practice/eaf5b886bd6645dd9cfb5406f3753e15
通过每次移动之后,计算出光标指向的数字,和光标向下移动的位置,最后判断出屏幕上输出的数字
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
int a = in.nextInt();
in.nextLine();
char[] b = in.nextLine().toCharArray();
// 记录选中的歌曲的下标,从0开始
int index = 0;
// 记录在屏幕向下移动的位置
int move = 0;
for(int i = 0 ; i < b.length ; i ++){
// 计算每次移动之后,光标在屏幕上向下移动的位置
if(b[i] == 'U' && a<4 && move == 0){
move = a ;
}else if(b[i] == 'U' && index == 0){
move = 3 ;
}else if (b[i] == 'D' && index == a-1 ){
move = 0;
}else if (b[i] == 'D' && move < 3){
move ++;
}else if (b[i] == 'U' && move > 0 ){
move --;
}
// 计算每次移动之后,光标指向的位置
if(b[i] == 'U' && index == 0 ){
index = a-1;
}else if(b[i] == 'D' && index == a-1){
index = 0;
}else if(b[i] == 'U'){
index--;
}else{
index++;
}
}
StringBuffer str = new StringBuffer();
// 根据光标指向的元素和光标向下移动的位置,计算出屏幕上的数据
if(a<4){
for(int i = 1; i <=a ; i++){
str.append(i+" ");
}
}else{
int temp = index-move+1;
for(int i = 0 ; i<4 ; i++){
str.append(temp + i +" ");
}
}
System.out.println(str.toString());
System.out.println(index+1);
}
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
int a = in.nextInt();
in.nextLine();
char[] b = in.nextLine().toCharArray();
// 记录选中的歌曲的下标,从0开始
int index = 0;
// 记录在屏幕向下移动的位置
int move = 0;
for(int i = 0 ; i < b.length ; i ++){
// 计算每次移动之后,光标在屏幕上向下移动的位置
if(b[i] == 'U' && a<4 && move == 0){
move = a ;
}else if(b[i] == 'U' && index == 0){
move = 3 ;
}else if (b[i] == 'D' && index == a-1 ){
move = 0;
}else if (b[i] == 'D' && move < 3){
move ++;
}else if (b[i] == 'U' && move > 0 ){
move --;
}
// 计算每次移动之后,光标指向的位置
if(b[i] == 'U' && index == 0 ){
index = a-1;
}else if(b[i] == 'D' && index == a-1){
index = 0;
}else if(b[i] == 'U'){
index--;
}else{
index++;
}
}
StringBuffer str = new StringBuffer();
// 根据光标指向的元素和光标向下移动的位置,计算出屏幕上的数据
if(a<4){
for(int i = 1; i <=a ; i++){
str.append(i+" ");
}
}else{
int temp = index-move+1;
for(int i = 0 ; i<4 ; i++){
str.append(temp + i +" ");
}
}
System.out.println(str.toString());
System.out.println(index+1);
}
}
}