Skip to content

Commit 08be2c0

Browse files
committed
Add palindrome number checker
1 parent b9c118f commit 08be2c0

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

math/palindrome_number.cpp

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/**
2+
* @file
3+
* @brief Check if a number is a [palindrome number](https://en.wikipedia.org/wiki/Palindrome)
4+
*
5+
* @details
6+
* A palindrome number is a number that reads the same forward and backward.
7+
* Examples: 121, 1331, 5445.
8+
*
9+
* This implementation reverses the digits of the number and compares it
10+
* with the original value.
11+
*
12+
* @author [Aman Keshav Prasad](https://github.com/amank-23)
13+
*/
14+
15+
#include <cassert> /// for assert
16+
#include <iostream> /// for IO operations
17+
18+
/**
19+
* @namespace math
20+
* @brief Mathematical algorithms
21+
*/
22+
namespace math {
23+
24+
/**
25+
* @brief Function to check if a given number is a palindrome.
26+
* @param num number to check
27+
* @return true if num is pallindrome, false otherwise
28+
*/
29+
bool is_palindrome(int num) {
30+
if (num < 0) {
31+
return false; // negative numbers are not palindrome
32+
}
33+
34+
int original = num;
35+
int reversed = 0;
36+
37+
while (num > 0) {
38+
int digit = num % 10;
39+
reversed = reversed * 10 + digit;
40+
num /= 10;
41+
}
42+
43+
return original == reversed;
44+
}
45+
46+
} // namespace math
47+
48+
/**
49+
* @brief Self-test implementations
50+
*/
51+
static void tests() {
52+
assert(math::is_palindrome(121) == true);
53+
assert(math::is_palindrome(5445) == true);
54+
assert(math::is_palindrome(10) == false);
55+
assert(math::is_palindrome(123) == false);
56+
assert(math::is_palindrome(-121) == false);
57+
assert(math::is_palindrome(0) == true);
58+
59+
std::cout << "All tests have successfully passed!\n";
60+
}
61+
62+
/**
63+
* @brief Main function
64+
*/
65+
int main() {
66+
tests();
67+
return 0;
68+
}

0 commit comments

Comments
 (0)