Here is the code:
def intToStr(i):
digits = '0123456789'
if i == 0:
return '0'
result = ''
while i > 0:
result = digits[i%10] + result
i = i/10
return result
I understand that with logarithmic complexity, you are essentially dividing the necessary steps by some value each time you iterate (for example binary search algorithm). However in this example, we are not really dividing by a number, instead we remove one letter at a time. So by dividing i
by 10 in i/10
, we eliminate one number at a time. I can't really wrap my head around this algorithm... Is there a name for this algorithm so I can better understand why this is logarithmic?
Well lets look at the steps for 123
:
i result
123 ""
12 "3" -- after first iteration
1 "23" -- second iteration
0 "123" -- third iteration
For the number 123 we need 3 steps to convert it to a string. By doing further tests, we essentially see that the number of iterations is always equal to the number of digits of the number we want to convert. So for any n
we can say that the algorithm needs floor(log10(n)+1)
steps, which equals log(n)
in Big O Notation.
EDIT:
hammar's answer is much more informative on the details of the complexity (one could say he hit the nail right on the head (pun intended)) so if you want to exactly know the complexity and want to be able to refer to it correctly you should look into his answer otherwise I think this "pseudo-logarithmic" fulfils your needs.