Skip to content

Instantly share code, notes, and snippets.

@ochukai
Created August 24, 2017 02:26
Show Gist options
  • Select an option

  • Save ochukai/f4c6dad0e38e666e282f9e42517d6625 to your computer and use it in GitHub Desktop.

Select an option

Save ochukai/f4c6dad0e38e666e282f9e42517d6625 to your computer and use it in GitHub Desktop.
环坐报数然后走的一个题目,求最后谁留下~
function Person(num) {
this.next = null; // 隔壁是谁
this.num = num; // 编号
this.isLeave = 0; // 没走
}
var max = 100;
var all = [];
for (var i = 0; i < max; i ++) {
// 初始化 1-100 人的编号
all.push(new Person(i + 1));
}
// 设置他们团团坐,每个人的下一个人是下一个编号的人。
var prev = all[0];
for (var j = 1; j < all.length; j ++) {
var next = all[j];
prev.next = next;
prev = next;
}
prev.next = all[0];
var number = 0; // 报的数
var leaveCount = 0; // 退出的人数
var current = all[0];
while(leaveCount !== (max - 1)) {
if (current.isLeave === 0) {
number ++; // 报数
// 报 3 就走
if (number === 3) {
current.isLeave = 1;
leaveCount ++;
number = 0;
}
}
current = current.next;
}
// 循环结束后,答案已经出现了
for (var m = 0; m < max; m ++) {
if (all[m].isLeave === 0) {
console.log('最后留下:', all[m].num);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment