From 330a6e1aea94904edbc89d403d826f609bcfe094 Mon Sep 17 00:00:00 2001 From: Pralav Singh <174412353+pralav-25@users.noreply.github.com> Date: Fri, 25 Sep 2026 12:08:34 +0530 Subject: [PATCH] fix: correct digit counts at rounded logarithm boundaries --- algorithms/math/num_digits.py | 18 +++++++++++++----- tests/test_num_digits_boundaries.py | 19 +++++++++++++++++++ 2 files changed, 32 insertions(+), 5 deletions(-) create mode 100644 tests/test_num_digits_boundaries.py diff --git a/algorithms/math/num_digits.py b/algorithms/math/num_digits.py index a37268392..f5cbe6732 100644 --- a/algorithms/math/num_digits.py +++ b/algorithms/math/num_digits.py @@ -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 @@ -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 diff --git a/tests/test_num_digits_boundaries.py b/tests/test_num_digits_boundaries.py new file mode 100644 index 000000000..ffb2efcb0 --- /dev/null +++ b/tests/test_num_digits_boundaries.py @@ -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)))