When it's a power of 2 keep in mind that you can use a simple and fast shift expression: 1 << exponent
For example:
22 = 1 << 2 = (int) Math.pow(2, 2)
210 = 1 << 10 = (int) Math.pow(2, 10)
For larger exponents (over 31) use long instead:
232 = 1L << 32 = (long) Math.pow(2, 32)
BTW, in Kotlin you have shl instead of <<:
(Java) 1L << 32 = 1L shl 32 (Kotlin)
When it's a power of 2 keep in mind that you can use a simple and fast shift expression: 1 << exponent
For example:
22 = 1 << 2 = (int) Math.pow(2, 2)
210 = 1 << 10 = (int) Math.pow(2, 10)
For larger exponents (over 31) use long instead:
232 = 1L << 32 = (long) Math.pow(2, 32)
BTW, in Kotlin you have shl instead of <<:
(Java) 1L << 32 = 1L shl 32 (Kotlin)
Integers are only 32 bits. This means that its max value is 2^31 -1. As you see, for very small numbers, you quickly have a result which can't be represented by an integer anymore. That's why Math.pow uses double.
If you want arbitrary integer precision, use BigInteger.pow. But it's of course less efficient.
Videos
try-with-resources
Since Java 7, you should use try-with-resources on your Scanner for safe and efficient handling of the underlying I/O resource:
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
int number = scanner.nextInt();
// other operations
}
}
Mathematical approach
You may want to consider using a faster mathematical approach to test if the number is a positive power of two or not...
boolean result = number > 0 && ((number & (number - 1)) == 0);
\ is technically a power of two: \
There's actually a bit hack for this :
private static boolean isPowerOfTwo(int number) {
return number > 0 && ((number & (number - 1)) == 0);
}
(ref : Bit Twiddling hacks)
This exploits the fact, that in binary notation a power of two is a 1 followed by a number of 0's, and the number just below is all 1's equal to that number of 0's :
100000000 // number
& 011111111 // number - 1
-----------
000000000