Create a class: “Palindrome” with private data members: upper_limit (int), lower_limit (int) and parameterized constructor, which initializes the values of both data members. Apart from initialization, this constructor also displays the count of palindrome numbers from upper_limit to lower_limit. [Example: upper_limit:50, lower_limit:10, count of palindrome numbers is: 4(11 , 22, 33 and 44), also make sure the value of upper_limit should be greater than lower_limit].
#include <iostream>
#include <vector>
class Palindrome {
public:
Palindrome(int up, int low)
: upper_limit { up }
, lower_limit { low }
{
if(upper_limit <= lower_limit) {
std::cout << "Upper limit is lesser than lower one!";
}
else {
auto palindroms = GetPalindroms();
std::cout << "Count of palindrome numbers is: " << palindroms.size() << '(';
for(auto x: palindroms) std::cout << " " << x;
std::cout << " )\n";
}
}
bool IsPalindrom(int x) const {
std::vector<int> digits;
while(x) {
digits.push_back(x % 10);
x /= 10;
}
for(size_t i = 0, j = digits.size() - 1; i < j; i++, j--) {
if(digits[i] != digits[j]) return false;
}
return true;
}
std::vector<int> GetPalindroms() const {
std::vector<int> palindroms;
for(int i = lower_limit; i <= upper_limit; i++) {
if(IsPalindrom(i)) {
palindroms.push_back(i);
}
}
return palindroms;
}
private:
int upper_limit;
int lower_limit;
};
int main() {
Palindrome p(50, 10);
return 0;
}
Comments
Leave a comment