题解 | #MP3光标位置#
MP3光标位置
https://www.nowcoder.com/practice/eaf5b886bd6645dd9cfb5406f3753e15
#include <iostream>
#include <string>
using namespace std;
//MP3光标位置
class MP3CurPos {
private:
//歌曲数量
int n;
//命令
string s;
//当前光标位置
int pos;
//当前列表
int list[4];
private:
//向上
void up(void);
//向下
void down(void);
public:
//构造函数
MP3CurPos(const int n, const string s);
//析构函数
~MP3CurPos();
//执行命令
MP3CurPos& execute(void);
//输出当前列表和当前选中歌曲
void print(void)const;
};
MP3CurPos::MP3CurPos(const int n, const string s) {
this->n = n;
this->s = s;
this->pos = 1;
for (int i = 1; (i <= this->n) && (i <= 4); i++)
this->list[i - 1] = i;
return;
}
MP3CurPos::~MP3CurPos() {
}
void MP3CurPos::up(void) {
//如果当前光标位置是第一首歌曲
if (this->pos == 1) {
this->pos = this->n;
//如果当前页面之外没有歌曲,当前列表不变,无需更新列表
if (this->n <= 4)
return;
//如果当前页面之外还有歌曲
if (this->n > 4) {
for (int i = 0; i < 4; i++)
this->list[3 - i] = this->n - i;
return;
}
}
//如果当前光标位置不是第一首歌曲
if (this->pos != 1) {
//如果当前光标位置不是当前列表的第一首歌曲,无需更新列表
if (this->pos != this->list[0]) {
this->pos--;
return;
}
//如果当前光标位置是当前列表的第一首歌曲
if (this->pos == this->list[0]) {
this->pos--;
for (int i = 0; i < 4; i++)
this->list[i]--;
return;
}
}
}
void MP3CurPos::down(void) {
//如果当前光标的位置是最后一首歌曲
if (this->pos == this->n) {
this->pos = 1;
//如果当前列表之外没有其他歌曲,无需更新列表
if (this->n <= 4)
return;
//如果当前列表之外还有其他歌曲
if (this->n > 4) {
for (int i = 0; i < 4; i++)
this->list[i] = i + 1;
return;
}
}
//如果当前光标位置不是最后一首歌曲
if (this->pos != this->n) {
//如果当前列表之外没有歌曲
//提前判断,避免遇到this->list[3]未初始化的情况
if (this->n <= 4) {
this->pos++;
return;
}
//如果当前光标位置不是当前列表的最后一首歌曲,无需更新列表
if (this->pos != this->list[3]) {
this->pos++;
return;
}
//如果当前光标位置是当前列表的最后一首歌曲
if (this->pos == this->list[3]) {
this->pos++;
for (int i = 0; i < 4; i++)
this->list[i]++;
return;
}
}
}
MP3CurPos& MP3CurPos::execute(void) {
for (int i = 0; i < this->s.size(); i++) {
if (this->s[i] == 'U')
this->up();
else if (this->s[i] == 'D')
this->down();
}
// TODO: 在此处插入 return 语句
return *this;
}
void MP3CurPos::print(void) const {
cout << this->list[0];
for (int i = 1; (i < 4) && (i < this->n); i++)
cout << ' ' << this->list[i];
cout << endl << this->pos << endl;
return;
}
int main() {
int n;
string s;
while (cin >> n >> s) { // 注意 while 处理多个 case
MP3CurPos(n, s).execute().print();
}
}
// 64 位输出请用 printf("%lld")

查看9道真题和解析