How to get the digits of a number without converting it to a string/ char array?

c++

Question

How do I get what the digits of a number are in C++ without converting it to strings or character arrays?

1
31
2/8/2011 4:03:49 AM

Accepted Answer

The following prints the digits in order of ascending significance (i.e. units, then tens, etc.):

do {
    int digit = n % 10;
    putchar('0' + digit);
    n /= 10;
} while (n > 0);
42
10/9/2012 5:35:34 PM

What about floor(log(number))+1?

With n digits and using base b you can express any number up to pow(b,n)-1. So to get the number of digits of a number x in base b you can use the inverse function of exponentiation: base-b logarithm. To deal with non-integer results you can use the floor()+1 trick.

PS: This works for integers, not for numbers with decimals (in that case you should know what's the precision of the type you are using).


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon