首页 > 解决方案 > 我今天在面试中被问到的棘手的 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) )

虽然它给出了某些场景的答案,但对于其他场景的答案仍然是错误的,有人可以告诉我我应该如何通过破解此代码来获得......谢谢......

标签: javascript

解决方案


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);

推荐阅读