How do I solve this C++ code project? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How do I solve this C++ code project?

In the code project of the Functions module/chapter 'Palindrome Numbers' all the test cases are passed except test case 5. I tried several times but It didn't work. Can anyone help? This is the code: #include <iostream> using namespace std; string reverse(string str){ int n = str.length(); for(int i=0; i<=n/2; i++){ swap(str[i], str[n-i-1]); } return str; } bool check_palindrome(string str){ string str_reversed = reverse(str); if(str_reversed==str){ return true; } else{ return false; } } int main() { string n; cin>>n; if(check_palindrome(n)) { cout <<n<<" is a palindrome"; } else { cout << n<<" is NOT a palindrome"; } return 0; }

25th May 2021, 5:15 PM
Aditya
Aditya - avatar
1 Answer
+ 2
In this case I would test if the reverse function was implemented correctly. Does it work for odd length strings? Does it work for even length strings? You can use small strings ( length 1 to 4 for example ), small enough to go line by line and work out what the code does to that string in your head. You'll see that reverse( "ab" ) returns "ab" instead of "ba" and reverse( "abcd" ) returns "dbca" instead of "dcba". But it works with odd strings. So something goes wrong at the center of the string. Most of the time this is because of a rounding error or an off-by-one error. And hey, you use a division/comparison in there so maybe it has to do with that. *hint* :) This is actually a very common debugging method that's called Rubber duck debugging. https://en.wikipedia.org/wiki/Rubber_duck_debugging https://en.wikipedia.org/wiki/Off-by-one_error
25th May 2021, 7:13 PM
Dennis
Dennis - avatar