• 暴力破解
// 暴力破解,时间复杂度O(log(n))
        function isPowerOf2(val) {
            let temp = 1;
            while (temp <= val) {
                if (temp === val) {
                    return true;
                }
                temp = temp * 2;
            }
            return false;
        }
        console.log(isPowerOf2(123));
        console.log(isPowerOf2(12234));
  • 位移运算,时间复杂度O(log(n))
   function isPowerOf2V2(val) {
            let temp = 1;
            while (temp <= val) {
                if (temp === val) {
                    return true;
                }
                temp = temp << 1;
            }
            return false;
        }
        console.log(isPowerOf2V2(123));
        console.log(isPowerOf2V2(12234));
  • 位运算 时间复杂度O(1)
  function isPowerOf2V3(val) {
            return (val & (val - 1)) === 0;
        }
        console.log(isPowerOf2V3(8));
        console.log(isPowerOf2V3(12234));

相关文章:

  • 2021-11-18
  • 2022-12-23
  • 2022-12-23
  • 2021-06-18
  • 2021-12-09
  • 2021-07-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-09-13
  • 2021-12-18
  • 2022-12-23
  • 2022-02-02
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案