0
How do I store the reversed value (Palindrome Module 4 C++)
My code: #include <iostream> using namespace std; bool isPalindrome(int x) { //complete the function int n, reversedNumber, remainder; x = reversedNumber; while( n != 0) { remainder = n%10; reversedNumber = reversedNumber*10 + remainder; n /= 10; } } int main() { int n; cin >>n; if(isPalindrome(n)) { cout <<n<<" is a palindrome"; } else { cout << n<<" is NOT a palindrome"; } return 0; } Would appreciate any help! :)
8 Antworten
+ 3
It should be
n = x;
and not
reversedNumber = x;
since the loop operates on 'n' as the copy of 'x', which is uninitialized right now. Everything else should be fine.
+ 2
Plaush
You have to assign value of x to n but assigned it to reverseNumber so here your n is 0 that's why while (n != 0) will not work
+ 1
Looks like you wanted to do
reversedNumber = x;
Instead of doing the exact opposite in the isPalindrome() function
+ 1
Plaush You are not returning a value from the function based on the code in your question. Return the bool value of the test. See code below:
#include <iostream>
using namespace std;
bool isPalindrome(int x) {
//complete the function
int reversed, digit, num = x;
while (num>0) {
digit = num % 10;
reversed = reversed * 10 + digit;
num = num / 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
Arsenic Tried that didn’t work. It just swap the ‘succesful and unsuccesful’ test around, if that makes any sense
E.G: My original code causes Test 1 to be correct but not test 2. Tried flipping x around, Test 2 is now correct but not Test 1
Edit: It didn’t swap, was probably seeing things, it still doesn’t work though :(
0
Plaush
In method return true if original number and reversed number are same otherwise return false.
0
Shadow Thank you so much! I can’t believe I didn’t know that :)
- 1
Tried Martin Taylor’s suggestion too, didn’t work.
Code:
#include <iostream>
using namespace std;
bool isPalindrome(int x) {
//complete the function
int n, reversedNumber = 0, remainder;
reversedNumber = x;
while( n != 0) {
remainder = n%10;
reversedNumber = reversedNumber*10 + remainder;
n /= 10;
}
if (reversedNumber==x){
return true;
}
else {
return false;
}
}
int main() {
int n;
cin >>n;
if(isPalindrome(n)) {
cout <<n<<" is a palindrome";
}
else {
cout << n<<" is NOT a palindrome";
}
return 0;
}
Edit: I know that there’s a simplier way but I wanna try the ‘given’ method :)