TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
finding_number_of_digits_in_a_number.cpp
Go to the documentation of this file.
1
19#include <cassert>
20#include <cmath>
21#include <cstdint>
22#include <iostream>
23
32 uint64_t count = 0;
33
34 // iterate until `n` becomes 0
35 // remove last digit from `n` in each iteration
36 // increase `count` by 1 in each iteration
37 while (n != 0) {
38 // we can also use `n = n / 10`
39 n /= 10;
40 // each time the loop is running, `count` will be incremented by 1.
41 ++count;
42 }
43
44 return count;
45}
46
55 // log(0) is undefined
56 if (n == 0) {
57 return 0;
58 }
59
60 // to handle the negative numbers
61 if (n < 0) {
62 n = -n;
63 }
64
65 double count = floor(log10(n) + 1);
66
67 return count;
68}
69
74static void first_test() {
75 assert(finding_number_of_digits_in_a_number(5492) == 4);
77 assert(finding_number_of_digits_in_a_number(10000) == 5);
79 assert(finding_number_of_digits_in_a_number(100000) == 6);
82}
83
84static void second_test() {
92}
97int main() {
98 // run self-test implementations
99 first_test();
100 second_test();
101 std::cout << "All tests have successfully passed!\n";
102 return 0;
103}
uint64_t finding_number_of_digits_in_a_number(uint64_t n)
for log calculation
static void first_test()
Self-test implementations.
double finding_number_of_digits_in_a_number_using_log(double n)
This function finds the number of digits in constant time using logarithmic function TC: O(1)
int main()
Main function.