JavaScript算法试题系列-10 发表于 2017-06-15 | 更新于 2017-06-15 | 分类于 学习笔记 , JavaScript | | 共 137 字 | 阅读 次 问题描述: 12345// 数字判断是否为 2 的指数值isPowerOfTwo(4); // trueisPowerOfTwo(64); // trueisPowerOfTwo(1); // trueisPowerOfTwo(0); // falseisPowerOfTwo(-1); // false 解答: 123456789101112131415161718// For the non-zero case:function isPowerOfTwo(number) { // `&` uses the bitwise n. // In the case of number = 4; the expression would be identical to: // `return (4 & 3 === 0)` // In bitwise, 4 is 100, and 3 is 011. Using &, if two values at the same // spot is 1, then result is 1, else 0. In this case, it would return 000, // and thus, 4 satisfies are expression. // In turn, if the expression is `return (5 & 4 === 0)`, it would be false // since it returns 101 & 100 = 100 (NOT === 0) return number & (number - 1) === 0;}// For zero-case:function isPowerOfTwoZeroCase(number) { return (number !== 0) && ((number & (number - 1)) === 0);} ------ 本文结束 ------ 版权声明 加州提子面包 by MiG is licensed under a Creative Commons BY-NC-SA 4.0 International License. 由MiG创作并维护的加州提子面包博客采用「创作共用保留署名-非商业性使用-相同方式共享」4.0国际许可证. 本文首发于加州提子面包 博客( https://gihcctpd.github.io ),版权所有,侵权必究.