Finding the string length of a integer in .NET

后端 未结 6 611
小鲜肉
小鲜肉 2020-12-28 18:12

In .NET what is the best way to find the length of an integer in characters if it was represented as a string?

e.g.

1 = 1 character
10 = 2 characters

6条回答
  •  [愿得一人]
    2020-12-28 18:41

    You can do:

    int ndig = 1;
    if (n < 0){n = -n; ndig++;}
    if (n >= 100000000){n /= 100000000; ndig += 8;}
    if (n >=     10000){n /=     10000; ndig += 4;}
    if (n >=       100){n /=       100; ndig += 2;}
    if (n >=        10){n /=        10; ndig += 1;}
    

    or something along those lines. It takes 4 comparisons and 0-4 divisions.

    (On 64 bits you have to add a fifth level.)

提交回复
热议问题