Home > Software engineering >  boolean function returning false even though condition is satisfied to return true in c . Why?
boolean function returning false even though condition is satisfied to return true in c . Why?

Time:05-11

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?

CodePudding user response:

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

CodePudding user response:

If it were up to me, I'd do the job rather differently.

std::string has a constructor to build a string for a pair of iterators. It also supports reverse iterators. As such, you can construct a reversed string a bit more easily like this:

std::string test_s_reversed(test_s.rbegin(), test_s.rend());

...but given how much that simplifies the task, you can boil most of it down to something like this:

bool is_palindrome(std::string const &s) { 
    return s == std::string(s.rbegin(), s.rend());
}

Implementation for an integer would then be something like this:

bool is_palindrome(int val) {
    return is_palindrome(std::to_string(val));
}

C.A.R. Hoare once commented that:

There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies.

I advise striving for the former.

  • Related