proper implementation to find next palindrome from SPOJ

浪尽此生 提交于 2020-01-05 08:12:17

问题


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;
}

来源:https://stackoverflow.com/questions/29115593/proper-implementation-to-find-next-palindrome-from-spoj

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!