Algorithm:
Store each input into std::vector v;
Compare its first (i=0) and last element(j=v.size()-1)
if (v[i] != v[j]) return false;
Compare its 2nd and 2nd to last element
if (v[i+1] != v[j-1]) return false;
until i meets j
======= C++ Code (efficient and O(N) =========
#include
#include
bool isPalindrome(const std::vector &v) {
size_t len = v.size();
if ( len < 2 )
return false;
int i = 0;
int j = len - 1;
while ( i < j ) {
if (v[i] != v[j])
return false;
++i;
--j;
}
return true;
}
int main() {
std::vector v;
int i;
bool found = false;
while (std::cout << "Enter a non-negative integer
(-1 to end):" && std::cin >> i && i != -1){
v.push_back(i);
if (isPalindrome(v) ) {
std::cout << "Your entered integers form a Palindrome\n";
found = true;
break;
}
}
if (found) {
copy(v.begin(), v.end(), std::ostream_iterator(std::cout, " "));
std::cout << std::endl;
std::cout << "Is a Palindrome\n";
}
else
std::cout << "Not a Palindrome\n";
return 0;
}