Skip to content

Commit 3fa2081

Browse files
authored
Add count_digits function with test cases
This PR adds a simple function to count the number of digits in an integer. Includes basic test cases using assert. Follows the style used in other math algorithms.
1 parent b9c118f commit 3fa2081

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

math/count_digits.cpp

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
#include <iostream>
2+
#include <cassert>
3+
4+
// returns how many digits the number has
5+
int count_digits(int n) {
6+
if (n == 0) return 1;
7+
8+
int c = 0;
9+
while (n > 0) {
10+
c++;
11+
n /= 10;
12+
}
13+
return c;
14+
}
15+
16+
void test() {
17+
assert(count_digits(12345) == 5);
18+
assert(count_digits(9) == 1);
19+
assert(count_digits(1000) == 4);
20+
assert(count_digits(0) == 1);
21+
}
22+
23+
int main() {
24+
test();
25+
std::cout << "Tests passed\n";
26+
return 0;
27+
}

0 commit comments

Comments
 (0)