题解 | 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;
}

全部评论

相关推荐

路过的咸蛋超人也想拿offer:你是我见过最美的牛客女孩
点赞 评论 收藏
分享
牛客10001:G了+1,被前端/客户端给捞起来了,不太想面
投递美团等公司7个岗位 美团求职进展汇总
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务