Fastest way to obtain a power of 10

Xerus picture Xerus · Oct 27, 2017 · Viewed 12k times · Source

I'll use Java as an example here, as it may be completely language-specific, but I'm generally interested in ways to do this.
Of course, the simplest and obvious way is this:

Math.pow(10, x)

but as far as I know, power is a fairly expensive operation. Thus I thought that there should be a better way, because it seems so obvious - I just need x zeroes after the 1!

Edit: Yes, this may be premature optimisation. The context is a rounding operation to n decimal places, which often uses something like this:

private final static int[] powersOf10 = {1, 10, 100, 1000, 10000};
public static double round(double number, int decimals) {
    if(decimals < 5)
        return Math.rint(number / powersOf10[decimals]) * powersOf10[decimals];
    double c = Math.pow(10, decimals);
    return Math.rint(number * c) / c;
}

This is the current rounding function I use, as you can see I already use a lookup table for the most used values, but I'm still curious whether there's some bit-magic or the like to improve this.

Answer

Louis Wasserman picture Louis Wasserman · Oct 27, 2017

The fastest way is

static final int[] POWERS_OF_10 = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000};
static int powerOfTen(int pow) {
  return POWERS_OF_10[pow];
}

...since no higher power of ten fits into an int. Sorry if you were expecting something cooler.