diff --git a/math/finding_number_of_digits_in_a_number.cpp b/math/finding_number_of_digits_in_a_number.cpp index ecbd76b91..93e151358 100644 --- a/math/finding_number_of_digits_in_a_number.cpp +++ b/math/finding_number_of_digits_in_a_number.cpp @@ -9,7 +9,7 @@ * number i.e, we can use it by inputting values whether it can be a * positive/negative value, let's say: an integer. There is also a second * method: by using "K = floor(log10(N) + 1)", but it's only applicable for - * numbers (not integers). + * numbers (not integers) code for that also included (count_digits). * For more details, refer to the * [Algorithms-Explanation](https://github.com/TheAlgorithms/Algorithms-Explanation/blob/master/en/Basic%20Math/Finding * the number of digits in a number.md) repository. @@ -17,10 +17,12 @@ #include /// for assert #include /// for IO operations +#include /// for log calculation /** * @brief The main function that checks * the number of digits in a number. + * TC : O(number of digits) * @param n the number to check its digits * @returns the digits count */ @@ -40,6 +42,29 @@ uint64_t finding_number_of_digits_in_a_number(uint64_t n) { return count; } +/** + * @brief This function finds the number of digits + * in constant time + * TC :O(1) + * @param n the number to check its digits + * @returns the digits count + */ +uint64_t count_digits(uint64_t n) { + // to handle the negative numbers + if(n < 0){ + n = -n; + } + + // log(0) is undefined + else if(n == 0){ + //handling the value 0 + return 0; + } + uint64_t count = floor(log10(n) + 1); + + return count; +} + /** * @brief Self-test implementations * @returns void @@ -52,15 +77,23 @@ static void test() { assert(finding_number_of_digits_in_a_number(100000) == 6); assert(finding_number_of_digits_in_a_number(13) == 2); assert(finding_number_of_digits_in_a_number(564) == 3); + assert(count_digits(5492) == 4); + assert(count_digits(-0) == 0); + assert(count_digits(10000) == 5); + assert(count_digits(9) == 1); + assert(count_digits(100000) == 6); + assert(count_digits(13) == 2); + assert(count_digits(564) == 3); std::cout << "All tests have successfully passed!\n"; } + /** * @brief Main function * @returns 0 on exit */ int main() { - test(); // run self-test implementations + test(); // run self-test implementations return 0; }