-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinteger_palindrome.h
More file actions
41 lines (34 loc) · 882 Bytes
/
Copy pathinteger_palindrome.h
File metadata and controls
41 lines (34 loc) · 882 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#ifndef CPP_ALGORITHM_INTEGER_PALINDROME_H
#define CPP_ALGORITHM_INTEGER_PALINDROME_H
#include <cmath>
namespace IntegerPalindrome
{
/**
* \brief Check if a number is a palindrome.
* \param x input number
* \return whether the number is a palindrome
*/
bool IsPalindromeNumber(int x);
}
// ----------------------------------------------------------------------------
inline bool IntegerPalindrome::IsPalindromeNumber(int x)
{
if (x <= 0)
{
return x == 0;
}
const int num_digits = static_cast<int>(std::floor(log10(x))) + 1;
int msd_mask = static_cast<int>(std::pow(10, num_digits - 1));
for (int i = 0; i < (num_digits / 2); ++i)
{
if (x / msd_mask != x % 10)
{
return false;
}
x %= msd_mask;
x /= 10;
msd_mask /= 100;
}
return true;
}
#endif