C++: how can I test if a number is power of ten?

前端 未结 9 1321
清歌不尽
清歌不尽 2021-02-18 19:12

I want to test if a number double x is an integer power of 10. I could perhaps use cmath\'s log10 and then test if x == (int) x?

<

9条回答
  •  南旧
    南旧 (楼主)
    2021-02-18 19:33

    Depending on the platform your code needs to run on the log might be very expensive.

    Since the amount of numbers that are 10^n (where n is natural) is very small, it might be faster to just use a hardcoded lookup table.

    (Ugly pseudo code follows:)

    bool isPowerOfTen( int16 x )
    {
      if( x == 10       // n=1
        || x == 100     // n=2
        || x == 1000    // n=3
        || x == 10000 ) // n=4
      return true;
    
      return false;
    }
    

    This covers the whole int16 range and if that is all you need might be a lot faster. (Depending on the platform.)

提交回复
热议问题