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

情到浓时终转凉″ 提交于 2019-11-27 12:38:07
Nicholas Mancuso

This should do it:

int length = (number ==0) ? 1 : (int)Math.log10(number) + 1;
int length = (int)Math.Log10(Math.Abs(number)) + 1;

You may need to account for the negative sign..

jheriko

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;
cjk

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

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

might do what you want.

You can use a while loop, which will likely be faster than a logarithm because this uses integer arithmetic only:

int len = 0;
while (n > 0) {
    len++;
    n /= 10;
}

I leave it as an exercise for the reader to adjust this algorithm to handle zero and negative numbers.

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..

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.

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

achinda99

You can loop through and delete by 10, count the number of times you loop;

int num = 423;
int minimum = 1;
while (num > 10) {
    num = num/10;
    minimum++;
}

Okay, I can't resist: use /=:

#include <stdio.h>

int
main(){
        int num = 423;
        int count = 1;
        while( num /= 10)
                count ++;
        printf("Count: %d\n", count);
        return 0;
}
534 $ gcc count.c && ./a.out
Count: 3
535 $ 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!