In the same vein as Martin Smith's answer, you could store all powers of 10 in order in an array and then do a binary search:
private static final long[] powersOf10 = new long[] {
1L, 10L, 100L, 1000L, 10000L, 100000L, 1000000L, 10000000L,
100000000L, 1000000000L, 10000000000L, 100000000000L,
1000000000000L, 10000000000000L, 100000000000000L, 1000000000000000L,
10000000000000000L, 100000000000000000L, 1000000000000000000L
};
static boolean isPowerOfTen(long input) {
return Arrays.binarySearch(powersOf10, input) >= 0;
}
Note: this method is far less efficient than Martin's (about 2.5x as slow on my computer) for this small data set but it scales much better to large data sets.
On the other hand, if you need extreme speed then this algorithm, based on 5gon12eder's comment, might be worth using. It switches on the lower bits of the input (you can't switch on a long) and if it gets a hit, it performs a linear search.
static boolean isPowerOfTen(long input) {
switch ((int)input) {
case (int)1L:
case (int)10L:
case (int)100L:
case (int)1000L:
case (int)10000L:
case (int)100000L:
case (int)1000000L:
case (int)10000000L:
case (int)100000000L:
case (int)1000000000L:
case (int)10000000000L:
case (int)100000000000L:
case (int)1000000000000L:
case (int)10000000000000L:
case (int)100000000000000L:
case (int)1000000000000000L:
case (int)10000000000000000L:
case (int)100000000000000000L:
case (int)1000000000000000000L:
return linearSearch(input);
default:
return false;
}
}
// from Martin Smith's answer:
private static boolean linearSearch(long input) {
return
input == 1L
|| input == 10L
|| input == 100L
|| input == 1000L
|| input == 10000L
|| input == 100000L
|| input == 1000000L
|| input == 10000000L
|| input == 100000000L
|| input == 1000000000L
|| input == 10000000000L
|| input == 100000000000L
|| input == 1000000000000L
|| input == 10000000000000L
|| input == 100000000000000L
|| input == 1000000000000000L
|| input == 10000000000000000L
|| input == 100000000000000000L
|| input == 1000000000000000000L;
}
Benchmark computing on first billion positive ints:
- linear search (Martin Smith): 2970 ms
- binary search: 6908 ms
- switch on hash then linear search: 1519 ms
1
is a power of 10 though, since 10 to the power of 0 is 1. This function returns false for 1. \$\endgroup\$ – Daniel Martin Jan 20 '16 at 21:13