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; +}