We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
1.假设N个猴子围成一圈,从 1 开始报数,数到 M 的猴子退出。第二轮倒着数,数到 M 的猴子退出。。。以此类推,最后剩下的猴子就是大王 2.写出函数,返回当选大王的猴子的最初位置
1
M
假设参数 (n,m),输入(3,2)
(n,m)
(3,2)
就生成编号为 [0,1,2] 的三只猴子,这个编号也就是猴子的最初位置,到时候把编号返回就可以了
[0,1,2]
话说回来,输入(3,2) 生成的数组就是 [0,1,2]
比如一轮报数,编号 0 首先报 1,编号1 报2,然后编号1的报数等于M,就是等于2,所以编号 1 要退出,所以猴子剩余 [0,2]。
0
2
[0,2]
第二轮报数,由于倒着数,需要把猴子数组反转一下。就变成了[2,0]
[2,0]
然后报数,编号2报1,编号0报2,然后编号0退出,此时猴子只剩下编号2,那么编号2的猴子就是大王。然后编号2,就是 2 就是当选大王的最初位置。把 2 返回就好
function handle(n,m){ let arr=[...Array.from({length:n}).keys()] let _index=0 while(arr.length>1){ _index=m%arr.length _index=_index?_index:arr.length arr.splice(_index-1,1) arr=arr.reverse() } return arr[0] } handle(3,4) //2 handle(5,9) //0
The text was updated successfully, but these errors were encountered:
No branches or pull requests
1.假设N个猴子围成一圈,从
1
开始报数,数到M
的猴子退出。第二轮倒着数,数到M
的猴子退出。。。以此类推,最后剩下的猴子就是大王2.写出函数,返回当选大王的猴子的最初位置
假设参数
(n,m)
,输入(3,2)
就生成编号为
[0,1,2]
的三只猴子,这个编号也就是猴子的最初位置,到时候把编号返回就可以了话说回来,输入
(3,2)
生成的数组就是[0,1,2]
比如一轮报数,编号
0
首先报1
,编号1
报2
,然后编号1
的报数等于M
,就是等于2
,所以编号1
要退出,所以猴子剩余[0,2]
。第二轮报数,由于倒着数,需要把猴子数组反转一下。就变成了
[2,0]
然后报数,编号
2
报1
,编号0
报2
,然后编号0
退出,此时猴子只剩下编号2
,那么编号2
的猴子就是大王。然后编号2
,就是2
就是当选大王的最初位置。把2
返回就好The text was updated successfully, but these errors were encountered: