MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / num_digits

Function num_digits

maths/number_of_digits.py:5–35  ·  view source on GitHub ↗

Find the number of digits in a number. >>> num_digits(12345) 5 >>> num_digits(123) 3 >>> num_digits(0) 1 >>> num_digits(-1) 1 >>> num_digits(-123456) 6 >>> num_digits('123') # Raises a TypeError for non-integer input Traceback (most recent call

(n: int)

Source from the content-addressed store, hash-verified

3
4
5def num_digits(n: int) -> int:
6 """
7 Find the number of digits in a number.
8
9 >>> num_digits(12345)
10 5
11 >>> num_digits(123)
12 3
13 >>> num_digits(0)
14 1
15 >>> num_digits(-1)
16 1
17 >>> num_digits(-123456)
18 6
19 >>> num_digits('123') # Raises a TypeError for non-integer input
20 Traceback (most recent call last):
21 ...
22 TypeError: Input must be an integer
23 """
24
25 if not isinstance(n, int):
26 raise TypeError("Input must be an integer")
27
28 digits = 0
29 n = abs(n)
30 while True:
31 n = n // 10
32 digits += 1
33 if n == 0:
34 break
35 return digits
36
37
38def num_digits_fast(n: int) -> int:

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected