Java, use (-n) & n skill

  • 1

    (-n) & n will get first 1 bit counting from right. If it equals n, it means n only has one 1 digit.

    public static boolean isPowerOfTwo(int n) {
        if (n <= 0) {
            return false;
        return n == (-n & n);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.