javascript - 我今天在面试中被问到的棘手的 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) )
虽然它给出了某些场景的答案,但对于其他场景的答案仍然是错误的,有人可以告诉我我应该如何通过破解此代码来获得......谢谢......
解决方案
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);
推荐阅读
- metronic - 如何将 metronic 主题集成到本地 formio 应用程序中
- sql-server - SQL 添加条件查询
- matlab - 如何从低通滤波器功能(firrrcos 或 rcosdesign)创建高通滤波器?MATLAB
- java - 通过 logger.log 覆盖处理程序级别
- encoding - 阿拉伯标签在 Geoserver 中无法正确显示
- javascript - 在 JavaScript 中等待 promise 时究竟会发生什么?
- git - 如何在不使用强制推送的情况下解决 rebase 冲突后将分支推送到远程?
- javascript - 如何在提示中添加内容并在节点程序中获取输出?
- java - 如何使用支持中断(暂停、连接丢失……)的 Spring Boot 开发获取端点?
- c - 当按位与应用于负数时会发生什么?