Get the number of digits in a number

0

I have been asked to make an algorithm in Python to know the number of digits in a number, is there a way to do it without the manipulation of strings ?

def achaTamanho(x):
    a = str(x)
    if len(a) > 1:
        if a[0] == '0':
            return len(a) - 1
        else:
            return len(a)
    return len(a)


num = int(input("Digite um número: "))
print(achaTamanho(num))
    
asked by anonymous 25.01.2018 / 22:22

2 answers

1

It's always better to do math. I made one use ready mathematical function and another without needing any module. It could simplify doing 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))
    
25.01.2018 / 23:12
-3

len (), is not a string manipulation, so the simplest way is: n = int (input ('Enter a number:')) print (n, 'tem', len (str (n)) , 'numbers')

    
25.01.2018 / 22:54