Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions algorithms/math/num_digits.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
"""
Number of Digits

Count the number of digits in an integer using logarithmic computation
for O(1) time complexity.
Count decimal digits using a logarithmic estimate corrected with integer
comparisons. Floating-point rounding at powers of ten cannot change the result.

Reference: https://en.wikipedia.org/wiki/Logarithm

Complexity:
Time: O(1)
Space: O(1)
Time: Integer exponentiation and comparisons depend on the number of digits.
Space: O(d) bits for d decimal digits (a constant number of integers).
"""

from __future__ import annotations
Expand Down Expand Up @@ -36,4 +36,12 @@ def num_digits(n: int) -> int:
n = abs(n)
if n == 0:
return 1
return int(math.log10(n)) + 1
digits = int(math.log10(n)) + 1
boundary = 10 ** (digits - 1)
while n < boundary:
digits -= 1
boundary //= 10
while n >= boundary * 10:
digits += 1
boundary *= 10
return digits
19 changes: 19 additions & 0 deletions tests/test_num_digits_boundaries.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"""Integer boundary oracles, including values beyond string conversion limits."""

import pytest

from algorithms.math.num_digits import num_digits


@pytest.mark.parametrize("exponent", [1, 2, 15, 16, 20, 100, 1000, 5000])
@pytest.mark.parametrize("sign", [-1, 1])
def test_neighbors_of_powers_of_ten(exponent, sign):
power = 10**exponent
assert num_digits(sign * (power - 1)) == exponent
assert num_digits(sign * power) == exponent + 1
assert num_digits(sign * (power + 1)) == exponent + 1


def test_small_integer_oracle():
for value in range(-2000, 2001):
assert num_digits(value) == len(str(abs(value)))