0
C++ Palindrome QuestionP
I am not sure how to connect the Bool to the result of the reversed number to check to see if it is a Palindrome. Numbers that are Palindromes are reading in the output as non-Palindromes. #include <iostream> using namespace std; bool isPalindrome(int x) { //complete the function while (x != 0) { int remainder = x % 10; int reversed = 0; reversed *= 10 + remainder; x /= 10; } } int main() { int n; cin >>n; if(isPalindrome(n)) { cout <<n<<" is a palindrome"; } else { cout << n<<" is NOT a palindrome"; } return 0; }
5 odpowiedzi
+ 3
Bool means a truth value. True. Or false. You get those among other things from expressions that are either true or false. For example comparisons of two values.
So, the one missing thing that returns the bool from your function is
return x == reversed;
But once you did that, you will notice that it does not operate correctly. Why is that? That is because
1) you have the variable declarations inside the loop. With every cycle you reset reversed to 0.
2) reversed *= 10 + remainder
is the same as rev = rev * (10 + remainder)
not rev = (rev * 10) + remainder
3) you destroy x in the process of reversing its digits. You need to make a working copy first.
+ 1
Why. In the world. Did you change return x == reversed; to this non-sensical if clause ???
0
I have tried this now and I am still getting non-Palindrome output when it is a Palindrome
#include <iostream>
using namespace std;
bool isPalindrome(int x) {
//complete the function
int remainder = 0;
int reversed = 0;
while (x != 0) {
remainder = x % 10;
reversed = (x * 10) + remainder;
x /= 10;
}
return x == reversed;
}
int main() {
int n;
cin >>n;
if(isPalindrome(n)) {
cout <<n<<" is a palindrome";
}
else {
cout << n<<" is NOT a palindrome";
}
return 0;
}
0
Look again at pt. 3. You destroy x. Make a copy of it, say int y = x; and use y in the loop.
0
#include <iostream>
using namespace std;
bool isPalindrome(int x) {
//complete the function
int num;
num = x;
int remainder = 0;
int reversed = 0;
while (num != 0){
remainder = num % 10;
reversed = (reversed * 10) + remainder;
num = num / 10;
}
if (x == reversed){
return true == x;
}
Still an issue
int main() {
int n;
cin >>n;
if(isPalindrome(n)) {
cout <<n<<" is a palindrome";
}
else {
cout << n<<" is NOT a palindrome";
}
return 0;
}