[LeetCode] ☆ power (if the power 4) to 342.4

description

Given an integer (32-bit signed integer), write a function to determine whether it is a power of 4.

Example 1:

Input: 16
Output: true
Example 2:

Input: 5
Output: false

Advanced:
You can not use a recursive loop or to complete this question it?

Resolve

And if the number is a power of 32 to 4, only the odd bit 1 has only one, the even bits are 0. Determine conditions:

1. 0xaaaaaaaa do with the calculation result is 0. (A = 1010)

2. num & (num - 1) == 0, only one of the described 1

Code

public boolean isPowerOfFour(int num) {
        if (num == 0) {
            return false;
        }
        if (((num & 0xaaaaaaaa) == 0) && (num & (num - 1)) == 0) {
            return true;
        } else {
            return false;
        }
    }
public boolean isPowerOfFour(int num) {
        if (((num & 0xaaaaaaaa) == 0) && (Integer.bitCount(num) == 1)) {
            return true;
        } else {
            return false;
        }
    }

 

Guess you like

Origin www.cnblogs.com/fanguangdexiaoyuer/p/11366495.html