How to find the length of a number
This article shows different approaches to finding the length of a number.
Whenever I ask this question during the interview, I find that candidates don't ever take some time to reflect on the reason for asking such a simple question rather they jump directly to solving the answer using the most commonly used method i.e. dividing the number by 10 till the number becomes
Below is the sample code for finding the length of a number using a loop and division method:
Now, what if I say that you're not allowed to use any loop.
Another approach to solving this will be using recursion. Below is the sample code for finding the length of a number using Recursion:
Now you can directly find the length of the number just by passing the number to the
count method and the method will return the length of the number.
Now, what if I say that you can't use any division
/ or modulus
% operator. Both of the above methods will become out of scope then.
Another approach will be to either convert the number into
string and then count its length or we can use
log base 10.
To find length using the log method, we have to find the log base 10 value of the number and add 1 to the floor of the value.
Below is the code to find the length of the number using
log in C (use
Math.h header file to use
There are more different approaches by which we can find the length of a number.
Another approach will be to first convert the number into a string and then find the length of the string. The following code shows how to find the length of a number using the string method.
Another approach will be to use a multiplication operator with a loop. This method is similar to the above-shown division with a loop method, instead, it uses a temporary variable and keeps multiplying by 10 in a loop, checks if the temporary variable is less than or equals to the number and keeps increasing the counter if the condition is satisfied. The following code shows how to find the length of a number using the multiplication with loop method.
The above-shown code samples are written in C, but you can find the complete code examples in different languages here: Github Repo
Please leave your questions and suggestions in the comment and share your thoughts or the best approach you can think of to solve the above problem.