|
| 1 | +/** |
| 2 | + * @author [aminos 🇮🇳](https://github.com/amino19) |
| 3 | + * @file |
| 4 | + * |
| 5 | + * @brief [Program to count digits |
| 6 | + * in an |
| 7 | + * integer](https://www.geeksforgeeks.org/program-count-digits-integer-3-different-methods) |
| 8 | + * @details It is a very basic math of finding number of digits in a given |
| 9 | + * number i.e, we can use it by inputting values whether it can be a |
| 10 | + * positive/negative value, let's say: an integer. There is also a second |
| 11 | + * method: by using "K = floor(log10(N) + 1)", but it's only applicable for |
| 12 | + * numbers (not integers). |
| 13 | + * For more details, refer to the |
| 14 | + * [Algorithms-Explanation](https://github.com/TheAlgorithms/Algorithms-Explanation/blob/master/en/Basic%20Math/Finding |
| 15 | + * the number of digits in a number.md) repository. |
| 16 | + */ |
| 17 | + |
| 18 | +#include <cassert> /// for assert |
| 19 | +#include <iostream> /// for IO operations |
| 20 | + |
| 21 | +/** |
| 22 | + * @brief The main function that checks |
| 23 | + * the number of digits in a number. |
| 24 | + * @param n the number to check its digits |
| 25 | + * @returns the digits count |
| 26 | + */ |
| 27 | +uint64_t finding_number_of_digits_in_a_number(uint64_t n) { |
| 28 | + uint64_t count = 0; ///< the variable used for the digits count |
| 29 | + |
| 30 | + // iterate until `n` becomes 0 |
| 31 | + // remove last digit from `n` in each iteration |
| 32 | + // increase `count` by 1 in each iteration |
| 33 | + while (n != 0) { |
| 34 | + // we can also use `n = n / 10` |
| 35 | + n /= 10; |
| 36 | + // each time the loop is running, `count` will be incremented by 1. |
| 37 | + ++count; |
| 38 | + } |
| 39 | + |
| 40 | + return count; |
| 41 | +} |
| 42 | + |
| 43 | +/** |
| 44 | + * @brief Self-test implementations |
| 45 | + * @returns void |
| 46 | + */ |
| 47 | +static void test() { |
| 48 | + assert(finding_number_of_digits_in_a_number(5492) == 4); |
| 49 | + assert(finding_number_of_digits_in_a_number(-0) == 0); |
| 50 | + assert(finding_number_of_digits_in_a_number(10000) == 5); |
| 51 | + assert(finding_number_of_digits_in_a_number(9) == 1); |
| 52 | + assert(finding_number_of_digits_in_a_number(100000) == 6); |
| 53 | + assert(finding_number_of_digits_in_a_number(13) == 2); |
| 54 | + assert(finding_number_of_digits_in_a_number(564) == 3); |
| 55 | + |
| 56 | + std::cout << "All tests have successfully passed!\n"; |
| 57 | +} |
| 58 | + |
| 59 | +/** |
| 60 | + * @brief Main function |
| 61 | + * @returns 0 on exit |
| 62 | + */ |
| 63 | +int main() { |
| 64 | + test(); // run self-test implementations |
| 65 | + return 0; |
| 66 | +} |
0 commit comments