
Count the digits of an integer in Python
Counting the digit of a integer looks easy but it's not actually easy.
a1 = 0
a2 = 3
a3 = 41
a4 = 123456789
d1 = len(str(a1))
d2 = len(str(a2))
d3 = len(str(a3))
d4 = len(str(a4))
print(d1) # 1
print(d2) # 1
print(d3) # 2
print(d4) # 9
The simplest way is converting a integer to a string and getting the length of it but this way is incorrect if the integer is negative. For, -3
contains the minus symbol.
Solution
def count_digit(n: int):
m = abs(n)
return len(str(m))
d1 = count_digit(3)
d2 = count_digit(-25)
d3 = count_digit(-0)
d4 = count_digit(456789)
print(d1) # 1
print(d2) # 2
print(d3) # 1
print(d4) # 6
count_digit
works for positive and negative integers.
Other solution
import math
def count_digit(n: int):
return int(math.log10(n)) + 1
print(count_digit(123)) # 3
print(count_digit(1234)) # 4
print(count_digit(12345)) # 5
log10
is the well known function to calculate an integer digit. The above works for only positive integers, so the next may be better.
import math
def count_digit(n: int):
if n == 0:
return 1
if 0 < n:
return int(math.log10(n)) + 1
if n < 0:
return int(math.log10(abs(n))) + 1
print(count_digit(240)) # 3
print(count_digit(0)) # 1
print(count_digit(-35)) # 2
@QED can calculate several logs of numbers at the same time. The command is log
and the default base is Napier's number. You can set the base with -b
option.
Comments
Powered by Markdown