I am attempting to reinvent the wheel by writing my own palindrome checking program in C++, using only basic loops and mathematical operations. I have arrived at a solution, but was wondering if it's the best solution and if it could be improved. I'm doing this primarily as a learning exercise. My code:
#include <iostream> // cout
#include <stdio.h> // printf
#include <string>
using namespace std;
bool is_palidrome(string inputString) {
int num_to_parse = inputString.size();
/* immediately return on single letter string as all single letter strings are palindromes -- saves CPU time as programme does not need to enter the loop */
if(num_to_parse == 1) {
return true;
}
for(int i=0; num_to_parse; i++) {
int point_end = num_to_parse - i - 1;
if(inputString[i] == inputString[point_end]) {
continue;
} else if (i == num_to_parse) {
return true;
} else {
return false;
}
}}
int main() {
// Change the value of inputString to test different palindromes
string inputString = "caabaac";
printf("%s", is_palidrome(inputString)?"This is a palindrome.":"Not a palindrome."); // ternary: test condition ? return this if true : return this if false
return 0;
}
I think at the moment I'm doing about 2x the number of loops I need to do, and so wasting CPU time. Also, there may be further optimizations. Any help really appreciated as I really want to understand this stuff properly and contribute to code-bases, rather than just doing everything with other people's higher-level code.