题解 | MP3光标位置
MP3光标位置
https://www.nowcoder.com/practice/eaf5b886bd6645dd9cfb5406f3753e15
#include <iostream> #include <string> using namespace std; // 函数用于打印当前显示的歌曲列表和选中的歌曲 void printCurrentList(int songCount, int cursorPosition, int displayStart) { // 计算当前屏幕显示的歌曲范围 int displayEnd = min(displayStart + 3, songCount - 1); // 打印当前显示的歌曲列表 for (int i = displayStart; i <= displayEnd; ++i) { cout << i + 1 << " "; } cout << endl; // 打印当前选中的歌曲 cout << cursorPosition + 1 << endl; } int main() { int songCount; // 歌曲总数 string commands; // 用户输入的命令序列 // 输入歌曲数量和命令序列 cin >> songCount; cin >> commands; // 初始化光标位置和显示起始位置 int cursorPosition = 0; // 光标初始位置为第0首歌(从0开始计数) int displayStart = 0; // 当前屏幕显示的起始歌曲位置 // 遍历命令序列,执行每个命令 for (char command : commands) { if (command == 'U') { // 按Up键 if (songCount <= 4) { // 歌曲总数小于等于4 cursorPosition = (cursorPosition - 1 + songCount) % songCount; // 循环移动光标 } else { // 歌曲总数大于4 if (cursorPosition == 0) { // 光标在第一首歌曲上 cursorPosition = songCount - 1; // 光标移到最后一首歌曲 displayStart = songCount - 4; // 显示最后一页 } else { // 光标不在第一首歌曲上 cursorPosition--; // 光标向上移动 if (cursorPosition < displayStart) { // 如果光标移出当前屏幕范围 displayStart = cursorPosition; // 更新显示起始位置 } } } } else if (command == 'D') { // 按Down键 if (songCount <= 4) { // 歌曲总数小于等于4 cursorPosition = (cursorPosition + 1) % songCount; // 循环移动光标 } else { // 歌曲总数大于4 if (cursorPosition == songCount - 1) { // 光标在最后一首歌曲上 cursorPosition = 0; // 光标移到第一首歌曲 displayStart = 0; // 显示第一页 } else { // 光标不在最后一首歌曲上 cursorPosition++; // 光标向下移动 if (cursorPosition > displayStart + 3) { // 如果光标移出当前屏幕范围 displayStart = cursorPosition - 3; // 更新显示起始位置 } } } } } // 打印最终的显示结果 printCurrentList(songCount, cursorPosition, displayStart); return 0; }