I’ve written before about how to tell if a number is an integer power of two, so I don’t know if you remember.

private static boolean test(int num) {
   return n > 0 && ((num & num - 1) = =0);
}
Copy the code

There’s another way to do it

The decimal system binary
1 1
2 10
4 100
8 1000
16 10000
32 100000
64 1000000

Is it 0’s after 1’s

Are we just going to make sure that everything is 0 except for the first one.

But how to get his binary…

Okay, I’ll look it up on the Internet. It’s down here

Integer.tobinaryString()
Copy the code

Let’s get started.

private static boolean test(int num) {
    // Check whether the number is greater than 0
    if (num > 0) {
        // If it is 1
        if (num == 1) {
            return true;
        }
        // Get binary
        String s = Integer.toBinaryString(num);
        // Remove the first element 1
        s = s.substring(1);
        int zero = Integer.parseInt(s, 2);
        if (zero == 0) {
            return true; }}return false;
}
Copy the code

So that’s how you get the answer. I have one line. You have a dozen. Is your company paid on a bank basis? Must simplify!

All right, let’s simplify it.

private static boolean test(int num) {
    return return n >0 && (Integer.highestOneBit(num) == num);
}
Copy the code

Q: What does integer.highestOneBit () do? Answer: is used to get the value represented by the leftmost bit (the other bits are 0).

So 101001 and 100001 are going to give you 100,000.

So what about the whole number of powers of 4? We’ll start right here.

Similarly, get the corresponding binary first

The decimal system binary
1 1
4 100
16 10000
64 1000000
256 100000000

It seems to have found a characteristic, like two more 00’s for each, that is, it only needs to satisfy the 1 followed by all zeros, and cut the number of zeros by an even number.

Return n >0 && (integer.highestOnebit (num) == num); Then get the length of the binary is odd (even number of zeros plus one). Integer.toBinaryString(num); ToBinaryString (num).length() % 2 ==1

So it turns out that

return num >0 && (Integer.highestOneBit(num) == num) && (Integer.toBinaryString(num).length() % 2= =1);
Copy the code

Personal public number “programmer xiao Zhu” welcome attention