I'm an entry level programmer and I usually work on javascript. I'm trying to improve my programming skills, and started working on SPOJ problems. I'm very new to Online programming.
Please have a look at this question
Input
The first line contains integer t, the number of test cases. Integers K are given in the next t lines.
Output For each K, output the smallest palindrome larger than K.
Below is my implementation. It is exceeding the given time limit to execute. What could be a better approach towards solving this? Please help.
#include <iostream>
#include <string>
using namespace std;
string getReverse(string str){
string reversedString = "";
double i = str.length();
while(--i >= 0){
reversedString += str[i];
}
return reversedString;
}
string incrementNumber(string str){
string nextValue = "";
long stringLength = str.length();
long i = 0;
char temp;
bool isNotIncremented = true;
int num[stringLength + 1];
num[0] = 0;
while (i++ < stringLength){
temp = str[i - 1];
num[i] = temp - 48;
}
for (i = stringLength; i > 0; i--){
if (isNotIncremented){
if ((num[i] + 1) <= 9){
num[i] = num[i] + 1;
isNotIncremented = false;
}
else{
num[i] = 0;
}
}
nextValue = ((char)(48 + num[i])) + nextValue;
}
if (isNotIncremented){
nextValue = "1" + nextValue;
}
return nextValue;
}
bool isPalindrome(string str){
return str == getReverse(str);
}
int main() {
// your code goes here
int numTestCases;
bool nextPalindromeNotFound;
string nextNumber;
cin >> numTestCases;
while(numTestCases--){
string input;
cin >> input;
nextPalindromeNotFound = true;
nextNumber = input;
while (nextPalindromeNotFound){
nextNumber = incrementNumber(nextNumber);
nextPalindromeNotFound = !(isPalindrome(nextNumber));
}
cout << nextNumber << endl;
}
return 0;
}