面试题:判断一个数是否是2的整数次幂

面试题:判断一个数是否是2的整数次幂

  • 暴力破解
// 暴力破解,时间复杂度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));
posted @ 2020-05-09 16:14  struggle_time  阅读(181)  评论(0编辑  收藏  举报