-
Notifications
You must be signed in to change notification settings - Fork 4
/
Check_if_number_is_Palindrome.cpp
74 lines (55 loc) · 1.21 KB
/
Check_if_number_is_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
// A recursive C++ program to check
// whether a given number
// is palindrome or not
#include <iostream>
using namespace std;
// A function that returns true only
// if num contains one
// digit
int oneDigit(int num)
{
// Comparison operation is faster
// than division
// operation. So using following
// instead of "return num
// / 10 == 0;"
return (num >= 0 && num < 10);
}
// A recursive function to find
// out whether num is
// palindrome or not. Initially, dupNum
// contains address of
// a copy of num.
bool isPalUtil(int num, int* dupNum)
{
// Base case (needed for recursion
// termination): This
// statement mainly compares the
// first digit with the
// last digit
if (oneDigit(num))
return (num == (*dupNum) % 10);
if (!isPalUtil(num / 10, dupNum))
return false;
*dupNum /= 10;
return (num % 10 == (*dupNum) % 10);
}
int isPal(int num)
{
if (num < 0)
num = -num;
int* dupNum = new int(num);
return isPalUtil(num, dupNum);
}
int main()
{
int n = 12321;
isPal(n) ? cout <<"Yes\n": cout <<"No" << endl;
n = 12;
isPal(n) ? cout <<"Yes\n": cout <<"No" << endl;
n = 88;
isPal(n) ? cout <<"Yes\n": cout <<"No" << endl;
n = 8999;
isPal(n) ? cout <<"Yes\n": cout <<"No";
return 0;
}