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