2021.09.28 - 093.2 的幂

1. 题目

在这里插入图片描述

2. 思路

(1) Integer.bitCount()

  • 2的幂次方的二进制位中只有1个1,调用Integer.bitCount()统计1的个数。

(2) 位运算

  • 2的幂次方与2的幂次方减1作与运算等于0。

(3) 取余

  • 2的幂次方必然能被2的30次方整除。

3. 代码

public class Test {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(Integer.toBinaryString(-2147483646));
    }
}

class Solution {
    
    
    public boolean isPowerOfTwo(int n) {
    
    
        return n > 0 && Integer.bitCount(n) == 1;
    }
}

class Solution1 {
    
    
    public boolean isPowerOfTwo(int n) {
    
    
        return n > 0 && (n & (n - 1)) == 0;
    }
}

class Solution2 {
    
    
    public boolean isPowerOfTwo(int n) {
    
    
        return n > 0 && (1 << 30) % n == 0;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44021223/article/details/120522370