Finding the length of an integer in C

C:

Why not just take the base-10 log of the absolute value of the number, round it down, and add one? This works for positive and negative numbers that aren’t 0, and avoids having to use any string conversion functions.

The log10, abs, and floor functions are provided by math.h. For example:

int nDigits = floor(log10(abs(the_integer))) + 1;

You should wrap this in a clause ensuring that the_integer != 0, since log10(0) returns -HUGE_VAL according to man 3 log.

Additionally, you may want to add one to the final result if the input is negative, if you’re interested in the length of the number including its negative sign.

Java:

int nDigits = Math.floor(Math.log10(Math.abs(the_integer))) + 1;

N.B. The floating-point nature of the calculations involved in this method may cause it to be slower than a more direct approach. See the comments for Kangkan’s answer for some discussion of efficiency.

Leave a Comment