How can I count the digits in an integer without a string cast?

前端 未结 10 1159
被撕碎了的回忆
被撕碎了的回忆 2020-12-03 00:54

I fear there\'s a simple and obvious answer to this question. I need to determine how many digits wide a count of items is, so that I can pad each item number with the m

10条回答
  •  无人及你
    2020-12-03 01:30

    A more efficient solution than repeated division would be repeated if statements with multiplies... e.g. (where n is the number whose number of digits is required)

    unsigned int test = 1;
    unsigned int digits = 0;
    while (n >= test)
    {
      ++digits;
      test *= 10;
    }
    

    If there is some reasonable upper bound on the item count (e.g. the 32-bit range of an unsigned int) then an even better way is to compare with members of some static array, e.g.

    // this covers the whole range of 32-bit unsigned values
    const unsigned int test[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };
    
    unsigned int digits = 10;
    while(n < test[digits]) --digits;
    

提交回复
热议问题