我今天在面试中被问到的棘手的javascript问题

时间:2019-07-19 02:50:50

标签: javascript

  

假设您有“ n个孩子围成一圈坐着”      和“ k”玩具可供分发      “ i”是开始的位置。   打印最后一个得到玩具的孩子

我的答案是

// n=5, k=3, i=1 // result 3

function get_last_kid(n,k,i)
{
  if(i==1)
  {
    return (k%n); //returns (toys/number of kids)
  }
  else
  {
    return (k%n)+i;
  }
}

alert( get_last_kid(3,7,3) )

在某些情况下,它给出了答案,但是在其他情况下,答案仍然是错误的,有人可以告诉我如何破解此代码。.谢谢...

1 个答案:

答案 0 :(得分:-1)

var n = 5; // childrend
var k = 8; // toys
var i = 3; // giving starts at



// get the last child to receive the toy if we start from 1st child 
var end = k%n;
// adjust if answer is 0 (there is no 0 position)
if (end == 0) end = n;
console.log(end);

// adjust end base on where the giving starts
var shouldbeend = end + (i - 1);
console.log(shouldbeend);

// adjust end base on the number of children (end can't go beyond the number of childrend)
var actualend = shouldbeend%n;
if (actualend == 0) actualend = n;
console.log(actualend);