It is always better to do it with math (well, it seems that Python is not so much, it is still good, but it is slow almost equally). I made one use mathematical function ready and another without needing any module. It could simplify making the division, but division costs more than multiplication.
import math
def achaTamanho(numero):
numero = abs(int(numero))
if numero < 2:
return 1
count = 0
valor = 1
while valor <= numero:
valor *= 10
count += 1
return count
def achaTamanho2(numero):
numero = abs(int(numero))
return (1 if numero == 0 else math.floor(math.log10(numero)) + 1)
print(achaTamanho(0))
print(achaTamanho(1))
print(achaTamanho(2))
print(achaTamanho(123))
print(achaTamanho(1000))
print(achaTamanho(-1))
print(achaTamanho(-23))
print(achaTamanho(45678))
print(achaTamanho(9999))
print ("")
print(achaTamanho2(0))
print(achaTamanho2(1))
print(achaTamanho2(2))
print(achaTamanho2(123))
print(achaTamanho2(1000))
print(achaTamanho2(-1))
print(achaTamanho2(-23))
print(achaTamanho2(45678))
print(achaTamanho2(9999))
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Logarithm in the base 10
– Jefferson Quesado
Details: https://answall.com/a/239881/64969
– Jefferson Quesado
Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).
– Maniero