河南县网站建设公司,仙桃哪里做网站,上海创意网站建设,物流公司Given an integer, write a function to determine if it is a power of two. Example 1: Input: 1
Output: true Example 2: Input: 16
Output: true Example 3: Input: 218
Output: false 这道题让我们判断一个数是否为2的次方数#xff0c;而且要求时间和空间复杂度都为常数… Given an integer, write a function to determine if it is a power of two. Example 1: Input: 1
Output: true Example 2: Input: 16
Output: true Example 3: Input: 218
Output: false 这道题让我们判断一个数是否为2的次方数而且要求时间和空间复杂度都为常数那么对于这种玩数字的题我们应该首先考虑位操作 Bit Operation。在LeetCode中位操作的题有很多比如比如 Repeated DNA SequencesSingle Number, Single Number II Grey Code Reverse BitsBitwise AND of Numbers RangeNumber of 1 Bits 和 Divide Two Integers 等等。那么我们来观察下2的次方数的二进制写法的特点 1 2 4 8 16 .... 1 10 100 1000 10000 .... 那么我们很容易看出来2的次方数都只有一个1剩下的都是0所以我们的解题思路就有了我们只要每次判断最低位是否为1然后向右移位最后统计1的个数即可判断是否是2的次方数代码如下 解法一 class Solution {
public:bool isPowerOfTwo(int n) {int cnt 0;while (n 0) {cnt (n 1);n 1;}return cnt 1;}
}; 这道题还有一个技巧如果一个数是2的次方数的话根据上面分析那么它的二进数必然是最高位为1其它都为0那么如果此时我们减1的话则最高位会降一位其余为0的位现在都为变为1那么我们把两数相与就会得到0用这个性质也能来解题而且只需一行代码就可以搞定如下所示 解法二 class Solution {
public:bool isPowerOfTwo(int n) {return (n 0) (!(n (n - 1)));}
}; 类似题目 Number of 1 Bits Power of Four Power of Three 参考资料 https://leetcode.com/problems/power-of-two/discuss/63974/Using-nand(n-1)-trick https://leetcode.com/problems/power-of-two/discuss/63972/One-line-java-solution-using-bitCount LeetCode All in One 题目讲解汇总(持续更新中...)