C++ - how to find the length of an integer

user1888527 picture user1888527 · Mar 26, 2014 · Viewed 169.4k times · Source

I'm trying to find a way to find the length of an integer (number of digits) and then place it in an integer array. The assignment also calls for doing this without the use of classes from the STL, although the program spec does say we can use "common C libraries" (gonna ask my professor if I can use cmath, because I'm assuming log10(num) + 1 is the easiest way, but I was wondering if there was another way).

Ah, and this doesn't have to handle negative numbers. Solely non-negative numbers.

I'm attempting to create a variant "MyInt" class that can handle a wider range of values using a dynamic array. Any tips would be appreciated! Thanks!

Answer

Kerrek SB picture Kerrek SB · Mar 26, 2014

The number of digits of an integer n in any base is trivially obtained by dividing until you're done:

unsigned int number_of_digits = 0;

do {
     ++number_of_digits; 
     n /= base;
} while (n);