algorithmlanguage-agnosticradixdigits

Fastest way to find the largest power of 10 smaller than x


Is there any fast way to find the largest power of 10 smaller than a given number?

I'm using this algorithm, at the moment, but something inside myself dies anytime I see it:

10**( int( math.log10(x) ) ) # python
pow( 10, (int) log10(x) )   // C

I could implement simple log10 and pow functions for my problems with one loop each, but still I'm wondering if there is some bit magic for decimal numbers.


Solution

  • An alternative algorithm is:

    i = 1;
    while((i * 10) < x)
        i *= 10;