-
Notifications
You must be signed in to change notification settings - Fork 1
/
palindrome.cpp
117 lines (97 loc) · 2.61 KB
/
palindrome.cpp
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
// {"category": "Algorithm", "notes": "Check if a number is palindrome"}
#include <SDKDDKVer.h>
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <Windows.h>
using namespace std;
//------------------------------------------------------------------------------
//
// Please implement a function that checks whether a positive number is a
// palindrome or not.
//
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//
// Implementation
//
//------------------------------------------------------------------------------
bool IsPalindrome(unsigned int number)
{
bool isPalindrome = false;
unsigned int reversed = 0;
const unsigned int copy = number;
bool overflow = false;
while (number != 0)
{
unsigned int digit = number % 10;
if (reversed > MAXUINT32 / 10)
{
overflow = true;
break;
}
reversed *= 10;
if (reversed > MAXUINT32 - digit)
{
overflow = true;
break;
}
reversed += digit;
number /= 10;
}
if (!overflow)
{
isPalindrome = (copy == reversed);
}
else
{
const int c_numberLength = 20;
char text[c_numberLength] = {};
sprintf(text, "%I64d", static_cast<__int64>(copy));
int length = strlen(text);
isPalindrome = true;
for (int i = 0; i < length / 2; i++)
{
if (text[i] != text[length - 1 - i])
{
isPalindrome = false;
break;
}
}
}
return isPalindrome;
}
//------------------------------------------------------------------------------
//
// Unit tests
//
//------------------------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
struct TestCase
{
unsigned int number;
bool isPalindrome;
};
const TestCase tests[] =
{
{ 121, true },
{ 123, false },
{ 0, true },
{ 99, true },
{ 4294884924, true },
{ MAXUINT32, false },
};
int countFailed = 0;
for (int i = 0; i < ARRAYSIZE(tests); i++)
{
if (IsPalindrome(tests[i].number) != tests[i].isPalindrome)
{
countFailed++;
cout << "Failed, number = " << tests[i].number << endl;
}
}
cout << ARRAYSIZE(tests) - countFailed << " passed, ";
cout << countFailed << " failed." << endl;
return 0;
}