C/C++ counting the number of decimals?

后端 未结 13 1964
北荒
北荒 2020-12-06 16:04

Lets say that input from the user is a decimal number, ex. 5.2155 (having 4 decimal digits). It can be stored freely (int,double) etc.

Is there any

13条回答
  •  旧巷少年郎
    2020-12-06 16:49

    If the decimal part of your number is stored in a separate int, you can just count the its decimal digits.

    This is a improvement on andrei alexandrescu's improvement. His version was already faster than the naive way (dividing by 10 at every digit). The version below is constant time and faster at least on x86-64 and ARM for all sizes, but occupies twice as much binary code, so it is not as cache-friendly.

    Benchmarks for this version vs alexandrescu's version on my PR on facebook folly.

    Works on unsigned, not signed.

    inline uint32_t digits10(uint64_t v) {
      return  1
            + (std::uint32_t)(v>=10)
            + (std::uint32_t)(v>=100)
            + (std::uint32_t)(v>=1000)
            + (std::uint32_t)(v>=10000)
            + (std::uint32_t)(v>=100000)
            + (std::uint32_t)(v>=1000000)
            + (std::uint32_t)(v>=10000000)
            + (std::uint32_t)(v>=100000000)
            + (std::uint32_t)(v>=1000000000)
            + (std::uint32_t)(v>=10000000000ull)
            + (std::uint32_t)(v>=100000000000ull)
            + (std::uint32_t)(v>=1000000000000ull)
            + (std::uint32_t)(v>=10000000000000ull)
            + (std::uint32_t)(v>=100000000000000ull)
            + (std::uint32_t)(v>=1000000000000000ull)
            + (std::uint32_t)(v>=10000000000000000ull)
            + (std::uint32_t)(v>=100000000000000000ull)
            + (std::uint32_t)(v>=1000000000000000000ull)
            + (std::uint32_t)(v>=10000000000000000000ull);
    }
    

提交回复
热议问题