I was asked in an interview recently how would I write an algorithm to count the number of digits in a given number. So for example if I was given a number 500 the result would be 3. If I was given a number 15345 the result would be 5.
I came up with 2 possible solutions:
Recursively divide the number by 10 until the result is less than 1 and then return the count of recursions I made.
Convert the number to string and then count the number of elements in this string.
Then I was asked which operation is more efficient when working with extremely large numbers and I couldn't give a good answer. So my question is what is the correct answer here - which algorithm is faster and why?
int
or even along
won't be enough. What language? – amitfloor(log_10(n)) + 1
– amit