Skip to content

Commit 0ec9f47

Browse files
[FEATURE] Add palindrome number checker (#3046)
1 parent b9c118f commit 0ec9f47

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

math/palindrome_number.cpp

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* @file
3+
* @brief Check whether a number is a palindrome.
4+
*/
5+
6+
#include <iostream>
7+
#include <cassert>
8+
9+
/**
10+
* @brief Checks if a number is a palindrome.
11+
* @param n Number to check
12+
* @return true if palindrome, false otherwise
13+
*/
14+
bool is_palindrome(int n) {
15+
if (n < 0) {
16+
return false; // negative numbers are not palindromes
17+
}
18+
int original = n;
19+
int reversed = 0;
20+
21+
while (n > 0) {
22+
reversed = reversed * 10 + (n % 10);
23+
n /= 10;
24+
}
25+
26+
return original == reversed;
27+
}
28+
29+
/**
30+
* @brief Self-test implementations
31+
*/
32+
static void tests() {
33+
assert(is_palindrome(121) == true);
34+
assert(is_palindrome(123) == false);
35+
assert(is_palindrome(0) == true);
36+
assert(is_palindrome(7) == true);
37+
assert(is_palindrome(-121) == false);
38+
39+
std::cout << "All tests passed!\n";
40+
}
41+
42+
/**
43+
* @brief Main function
44+
*/
45+
int main() {
46+
tests();
47+
return 0;
48+
}

0 commit comments

Comments
 (0)