MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / num_digits_fast

Function num_digits_fast

maths/number_of_digits.py:38–62  ·  view source on GitHub ↗

Find the number of digits in a number. abs() is used as logarithm for negative numbers is not defined. >>> num_digits_fast(12345) 5 >>> num_digits_fast(123) 3 >>> num_digits_fast(0) 1 >>> num_digits_fast(-1) 1 >>> num_digits_fast(-123456) 6 >>> n

(n: int)

Source from the content-addressed store, hash-verified

36
37
38def num_digits_fast(n: int) -> int:
39 """
40 Find the number of digits in a number.
41 abs() is used as logarithm for negative numbers is not defined.
42
43 >>> num_digits_fast(12345)
44 5
45 >>> num_digits_fast(123)
46 3
47 >>> num_digits_fast(0)
48 1
49 >>> num_digits_fast(-1)
50 1
51 >>> num_digits_fast(-123456)
52 6
53 >>> num_digits('123') # Raises a TypeError for non-integer input
54 Traceback (most recent call last):
55 ...
56 TypeError: Input must be an integer
57 """
58
59 if not isinstance(n, int):
60 raise TypeError("Input must be an integer")
61
62 return 1 if n == 0 else math.floor(math.log(abs(n), 10) + 1)
63
64
65def num_digits_faster(n: int) -> int:

Callers

nothing calls this directly

Calls 1

floorMethod · 0.80

Tested by

no test coverage detected