I have a number (64-bit int) and want to know if it's a pure power of 10. That is to say, a 1 followed 0 or more by zeroes. Is there an efficient way of doing this that does not involve turning it into a String?
Currently I'm doing this:
Kotlin
fun isPowerOf10(n: Long): Boolean {
val logN = Math.log10(myInt.toDouble())
return logN != Math.floor(logN)
}
Java
static boolean isPowerOf10(long n) {
double logN = Math.log10((double) myInt);
return logN != Math.floor(logN);
}
But it fails with isPowerOf10(999_999_999_999_999_999)
(and the negative version), due to precision loss when converting to a double and taking log10
, which outputs precisely 18.0
.