find the “string length” of an int

前端 未结 6 1865
情话喂你
情话喂你 2020-12-31 21:13

basically I want to return the number of digits in the int -> values like this:

(int)1 => 1
(int)123 => 3
(int)12345678 => 8

I kno

6条回答
  •  伪装坚强ぢ
    2020-12-31 21:37

    If your integer value (e.g. 12345678u) is a compile-time constant, you can let the compiler determine the length for you:

    template
    constexpr unsigned int_decimal_digits(T value)
    {
        return (    value / 10
                        ?   int_decimal_digits(value/10) + 1
                        :   1 );
    }
    

    Usage:

    unsigned n = int_decimal_digits(1234); 
    // n = 4
    
    #include 
    unsigned m = int_decimal_digits(ULLONG_MAX);
    // m = maximum length of a "long long unsigned" on your platform
    

    This way, the compiler will compute the number of decimal places automatically, and fill in the value as a constant. It should be the fastest possible solution, because there is no run-time computation involved and integer constants are usually put into the instruction opcodes. (This means that they travel by instruction pipeline, not by data memory/cache.) However, this requires a compiler that supports C++11.

提交回复
热议问题