From 3fa2081cc2bdc3f082e36c94f74c6d065890752d Mon Sep 17 00:00:00 2001 From: Aditya Date: Sat, 29 Nov 2025 19:42:38 +0530 Subject: [PATCH] Add count_digits function with test cases This PR adds a simple function to count the number of digits in an integer. Includes basic test cases using assert. Follows the style used in other math algorithms. --- math/count_digits.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 math/count_digits.cpp diff --git a/math/count_digits.cpp b/math/count_digits.cpp new file mode 100644 index 0000000000..e7fb5a91b5 --- /dev/null +++ b/math/count_digits.cpp @@ -0,0 +1,27 @@ +#include +#include + +// returns how many digits the number has +int count_digits(int n) { + if (n == 0) return 1; + + int c = 0; + while (n > 0) { + c++; + n /= 10; + } + return c; +} + +void test() { + assert(count_digits(12345) == 5); + assert(count_digits(9) == 1); + assert(count_digits(1000) == 4); + assert(count_digits(0) == 1); +} + +int main() { + test(); + std::cout << "Tests passed\n"; + return 0; +}