C++ Contar los dígitos de un número

Código para contar los dígitos de un número entero: Fuente

#include <cmath>
#include <limits>

// log10(x) == (n - 1) digits
// (1 + n + fff) == number of digits
// fff == floating-point fudge factor
int digits(int number)
{
// Avoid doing work if number is 0
if (number != 0)
{
double lg = std::log10(static_cast<double>(std::abs(number)));
double eps = std::numeric_limits<double>::epsilon();
return static_cast<int>(1 + lg + eps);
}
else
return 1;
}

// Count until 0 and chop of every tenth
int digits2(int num)
{
// Avoid doing work if number is 0
if (num != 0)
{
int n = 0;

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

return n;
}
else
return 1;
}

1 comentario:

Alf dijo...

¡Atención al segundo método cuando el número es negativo!