Search code examples
c++for-loopbooleanreturn-value

boolean function returning false even though condition is satisfied to return true in c++. Why?


My function is a simple palindrome algorithm that is supposed to take an input integer (test), turn it into a string (test_s), then reverse that string in a new variable (test_s_reverse) then return true if test_s is equal to test_s_reverse.

bool is_palindrome(int test){
    test_s = to_string(test);
    test_length = test_s.length();
    for (int i=(test_length + 1); i>=0; i--){
        test_s_reverse += test_s[i];
    }
    if (test_s_reverse == test_s){
        return true;
    }
    else {
        return false;
    }
}

I created a main function to test results and using input 12321 the program returns false, even though cout for test_s_reverse is = 12321 and test_s = 12321.

What am I doing wrong?


Solution

  • You should use test_length - 1 instead of test_lenght + 1, because in the new reversed string you have some extra characters which you can't see if you print them.

    The .length() function returns you exactly the number of characters in the string. So you either go with test_length, but you do i>0, or if you go in the loop with i>=0 you go with test_length - 1, so you will be sure that there are no blank characters at the end of new string.

    But, if you start with test_length, you will need to edit, since there is no character at test_length position:

    test_s_reverse += test_s[i-1];
    

    If you use pure C++ code, it should look like this:

    bool is_palindrome(int test){
        string test_s = to_string(test);
        int test_length = test_s.length();
        string test_s_reverse;
        for (int i=(test_length); i>0; i--){
            test_s_reverse += test_s[i-1];
        }
        if (test_s_reverse == test_s){
            return true;
        }
        else {
            return false;
        }
    }