Alex Rivera | Logout

How do I determine the number of digits of an integer in C?

Asked 2009-07-01T12:21:22.227
105

for instance,

n = 3432, result 4

n = 45, result 2

n = 33215, result 5

n = -357, result 3

I guess I could just turn it into a string then get the length of the string but that seems convoluted and hack-y.

Edit
Report

3 Answers

127
floor (log10 (abs (x))) + 1

http://en.wikipedia.org/wiki/Logarithm

answered 2009-07-01T12:24:02.953
26

Binary search pseudo algorithm to get no of digits of r in v..

if (v < 0 ) v=-v;

r=1;

if (v >= 100000000)
{
  r+=8;
  v/=100000000;
}

if (v >= 10000) {
    r+=4;
    v/=10000;
}

if (v >= 100) {
    r+=2;
    v/=100;
}

if( v>=10)
{
    r+=1;
}

return r;
answered 2009-07-01T12:42:00.843
4
if (x == MININT) return 10;  //  abs(MININT) is not defined
x = abs (x);
if (x<10) return 1;
if (x<100) return 2;
if (x<1000) return 3;
if (x<10000) return 4;
if (x<100000) return 5;
if (x<1000000) return 6;
if (x<10000000) return 7;
if (x<100000000) return 8;
if (x<1000000000) return 9;
return 10; //max len for 32-bit integers

Very inelegant. But quicker than all the other solutions. Integer Division and FP logs are expensive to do. If performance isn't an issue, the log10 solution is my favorite.

answered 2009-07-01T13:18:24.857

Your Answer