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
31
uint64_t
finding_number_of_digits_in_a_number
(uint64_t n) {
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
54
double
finding_number_of_digits_in_a_number_using_log
(
double
n) {
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
74
static
void
first_test
() {
75
assert(
finding_number_of_digits_in_a_number
(5492) == 4);
76
assert(
finding_number_of_digits_in_a_number
(-0) == 0);
77
assert(
finding_number_of_digits_in_a_number
(10000) == 5);
78
assert(
finding_number_of_digits_in_a_number
(9) == 1);
79
assert(
finding_number_of_digits_in_a_number
(100000) == 6);
80
assert(
finding_number_of_digits_in_a_number
(13) == 2);
81
assert(
finding_number_of_digits_in_a_number
(564) == 3);
82
}
83
84
static
void
second_test() {
85
assert(
finding_number_of_digits_in_a_number_using_log
(5492) == 4);
86
assert(
finding_number_of_digits_in_a_number_using_log
(-0) == 0);
87
assert(
finding_number_of_digits_in_a_number_using_log
(10000) == 5);
88
assert(
finding_number_of_digits_in_a_number_using_log
(9) == 1);
89
assert(
finding_number_of_digits_in_a_number_using_log
(100000) == 6);
90
assert(
finding_number_of_digits_in_a_number_using_log
(13) == 2);
91
assert(
finding_number_of_digits_in_a_number_using_log
(564) == 3);
92
}
97
int
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
}
finding_number_of_digits_in_a_number
uint64_t finding_number_of_digits_in_a_number(uint64_t n)
for log calculation
Definition
finding_number_of_digits_in_a_number.cpp:31
first_test
static void first_test()
Self-test implementations.
Definition
finding_number_of_digits_in_a_number.cpp:74
finding_number_of_digits_in_a_number_using_log
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)
Definition
finding_number_of_digits_in_a_number.cpp:54
main
int main()
Main function.
Definition
finding_number_of_digits_in_a_number.cpp:97
math
finding_number_of_digits_in_a_number.cpp
Generated by
1.12.0