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

前端 未结 10 1136
被撕碎了的回忆
被撕碎了的回忆 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:27

    This should do it:

    int length = (number ==0) ? 1 : (int)Math.log10(number) + 1;
    
    0 讨论(0)
  • 2020-12-03 01:28

    One solution is provided by base 10 logarithm, a bit overkill.

    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-12-03 01:33

    I would have posted a comment but my rep score won't grant me that distinction.

    All I wanted to point out was that even though the Log(10) is a very elegant (read: very few lines of code) solution, it is probably the one most taxing on the processor.

    I think jherico's answer is probably the most efficient solution and therefore should be rewarded as such.

    Especially if you are going to be doing this for a lot of numbers..

    0 讨论(0)
  • 2020-12-03 01:33

    Since a number doesn't have leading zeroes, you're converting anyway to add them. I'm not sure why you're trying so hard to avoid it to find the length when the end result will have to be a string anyway.

    0 讨论(0)
  • 2020-12-03 01:35

    If you are going to pad the number in .Net, then

    num.ToString().PadLeft(10, '0') 
    

    might do what you want.

    0 讨论(0)
提交回复
热议问题