I would like to know how I can find the length of an integer in C.
For instance:
- 1 => 1
- 25 => 2
- 12512 => 5
- 0 => 1
and so on.
How can I do this in C?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
C:
You could 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, andfloorfunctions are provided bymath.h. For example:You should wrap this in a clause ensuring that
the_integer != 0, sincelog10(0)returns-HUGE_VALaccording toman 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:
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.