-
Notifications
You must be signed in to change notification settings - Fork 16
/
palindromes.cpp
56 lines (49 loc) · 1.31 KB
/
palindromes.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
// A C++ program to generate palindromic numbers
// less than n.
#include <iostream>
using namespace std;
// A utility for creating palindrome
int createPalindrome(int input, int b, bool isOdd)
{
int n = input;
int palin = input;
// checks if number of digits is odd or even
// if odd then neglect the last digit of input in
// finding reverse as in case of odd number of
// digits middle element occur once
if (isOdd)
n /= b;
// Creates palindrome by just appending reverse
// of number to itself
while (n > 0)
{
palin = palin * b + (n % b);
n /= b;
}
return palin;
}
// Function to print decimal palindromic number
void generatePalindromes(int n)
{
int number;
// Run two times for odd and even length palindromes
for (int j = 0; j < 2; j++)
{
// Creates palindrome numbers with first half as i.
// Value of j decided whether we need an odd length
// of even length palindrome.
int i = 1;
while ((number = createPalindrome(i, 10, j % 2)) < n)
{
cout << number << " ";
i++;
}
}
}
// Driver Program to test above function
int main()
{
int n = 104;
generatePalindromes(n);
return 0;
}