简体   繁体   English

任何人都可以帮助我解决反游戏解决方案吗?

[英]Can anyone help me with Counter game solution?

When I try to run the input, it says that the time limit exceeded.当我尝试运行输入时,它说超出了时间限制。 Can anyone help me to reduce this code, thank you.谁能帮我减少这个代码,谢谢。

const counterGame = (n) => {
  let count = 0;

  for (let i = n; i > 0; i--) {
    if (Math.pow(2, i) % 1 === 0 && Math.pow(2, i) === n) {
      n /= 2;
      count++;
      if (n === 1) break;
    } else if (Math.pow(2, i) <= n) {
      n -= Math.pow(2, I);
      count++;
      if (n === 1) break;
    }
  }

  if (count % 2 === 0) {
    return 'Richard';
  } else {
    return 'Louise';
  }

};

You don't need to loop for just checking whether n is power of 2. Check whether this helps or not.您不需要循环仅检查 n 是否为 2 的幂。检查这是否有帮助。

const counterGame = (n) => {
if (n % 2 === 0) {
  return 'Richard';
    } else {
 return 'Louise';
}
 };

You don't have to iterate over the values to find if n is power of 2. You can use Math.log2() method.您不必遍历这些值来查找 n 是否为 2 的幂。您可以使用Math.log2()方法。 Like this,像这样,

 function counterGame(n) { let move = 0; while(n > 1) { let power = parseInt(Math.log2(n)); let max = 2**power; if(n === max) { n = parseInt(n/2); } else { n = n - max; } move++; } if(move %2 === 0) { return 'Richard'; } else { return 'Louise'; } } console.log(counterGame(6)); console.log(counterGame(8));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM