When negative numbers are not considered, for this analysis, we can see that when the input value is less than 1, this number is definitely not an integer power of 2.
When the input value is greater than one, we can find a rule. The integer power of 2 is expressed in binary as:
2d = 10b; 4d = 100b; 8d = 1000b
The first bit of the binary is one, and the rest are zero.
Therefore, we can judge that when the input value is converted to binary, the first bit is one and the other bits are 0, so that the input value is an integer power of 2.
However, doing this is too cumbersome. We can only judge the position of "1" in the binary number for the last time, and use the String, lastIndexOf(); method.
And we can also find that this rule also applies to the case where input 1 is entered.
Then the concise code came into being.
public static boolean isPowerOfTwo(int n) {String str = Integer.toBinaryString(n);if(n < 1)return false;else if(str.lastIndexOf("1") == 0)return true;elsereturn false; }The above java method to determine whether an integer power of 2 is the entire content shared by the editor. I hope it can give you a reference and I hope you can support Wulin.com more.