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

peoro picture peoro · Dec 22, 2010 · Viewed 7.8k times · Source

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.

Answer

Anon. picture Anon. · Dec 22, 2010

An alternative algorithm is:

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