algorithm - Counting the number of digits in a number - which of these two solutions is faster? -
I was recently told in an interview that how do I count the number of digits in a given number, an algorithm I will write So for example if the result of 500 was given to me then the result would be 3. If I was given 15345, the result would be 5.
I came up with 2 possible solutions:
-
Split the result to at least 1, until the result is less than 1 and then I have counted the revision I made.
-
Convert the number to string and then calculate the number of elements in this string.
Then I was asked which operation is more efficient and works a great number and I can not give a good answer. So my question is, what is the correct answer - which algorithm is fast and why?
Well, to change an integer in a string, the original ita
(integer for string) function functions to some extent:
result = "" while (number> gt; 0) {number = number% 10 digits number = Add digits for number / 10}
Therefore, there is not much difference between your first and second solution. The first solution will take o (n) iterations, where the number of digits in the n integer will be the same complexity in the second solution, and (2n) the total For hey (n) will calculate the digits n in the string, = o (n) complexity
Other algorithms are possible. For example, you can take a look at the highest bits set, and match those values with the table.
Comments
Post a Comment