Question:

Algorithm to determine decimal digits of an integer?

by  |  earlier

0 LIKES UnLike

Is there an algorithm to absolutely determine the number of digits the decimal form of an integer will have?

Example:

1,234 has 4 digits in decimal

It is easy to count the number manually, but this is useless when the number is given in binary or another base, without converting.

Example:

The binary number 10011010010 has 4 decimal digits

The hexadecimal number 4D2 has 4 decimal digits

So, given an integer, is there an algorithm that will determine the number of decimal digits it takes to represent?

This should be a mathematical manipulation, not converting to a character array in a programming languages and counting the size of the array.

 Tags:

   Report

2 ANSWERS


  1. Take the common log of n+1, then round up to the nearest integer using the 'ceiling' function.

    For example:

    n = 1234

    log(1245) = 3.09166696

    ceiling(3.09166696) = 4

    Or:

    n = 9999

    log(10000) = 4

    ceiling(4) = 4

    Or:

    n = 10000

    log(10001) = 4.00004343

    ceiling(4.00004343) = 5

    Note: If you are working with negative numbers, compute the value for the absolute value of n.

    Example:

    n = -12

    log(13) = 1.11394335

    ceiling(1.11394335) = 2

    Alternatively, rather than the form using ceiling you can use floor(log(|n|)) + 1.


  2. Well, if you are allowed to 'take the logarithm' then your set.  The number of decimal digits required would be the value to the left of the decimal point (of the base ten logarithm)... plus one

    Hence, for number N, whose common logarithm is 4.12, the number of decimal digits required is 4+1, or 5.

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions