+ 1

My only test case 4 is coming out to be wrong(C++)...Please tell what's gone wrong in my Code !!!

#include <iostream> using namespace std; bool isPalindrome(int x) { //complete the function int arr[x]; for(int i=0;i<x;i++){ if(arr[i]==arr[x-1]){ return true; } 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; }

15th Feb 2022, 5:23 PM
Sabnis Ashutosh
Sabnis Ashutosh - avatar
5 odpowiedzi
+ 3
bool isPalindrome(int x) { int tem = x; int rev = 0; while( x > 0){ rev = 10 * rev + x % 10; x /= 10; } if(rev == tem) return true; return false; }
15th Feb 2022, 6:22 PM
JaScript
JaScript - avatar
+ 2
Hint: to check if a number is palindrome, you need to reverse it and compare with the original one. The number is the parameter x of the functionisPalindrome. The digits of x need to be determined and after that reversed and compared.
15th Feb 2022, 5:38 PM
JaScript
JaScript - avatar
+ 2
I think you are very fortunate that only not passing 1 test case.. But your return all Palindromes for any input.. What your logic of using arr[I]==arr[x-1]? , when you are not assigned any values to array so initially working on garbage values., try in playground you may get different output for same values.. Your loop runs only ones always.. return causes to come out function on executed. palindrome number means reversing input number equal to input. ex: 121 234 is not. . your logic not related to reversing the number. you don't need array.. edit : n=125 input for example, rev=0; for reverse number 125%10 =5 append to rev, rev=5 make n=12 by 125/10 repeat these two steps until n>0 12%10=2, append to rev, rev=52 n=12/10=1 1%10=1, append to rev, rev=521 n=1/10=0 521 != 125 not palindrome. for input 121, n=121 and reverse=121 , it's palindrome. you need to give a try again for understanding your code.. hope it helps...
15th Feb 2022, 5:41 PM
Jayakrishna 🇮🇳
+ 1
I think you are passing the number you want to test to the function, but then treating it as the length of the number you want to test. So you want to get the length of x and then iterate through that.
15th Feb 2022, 5:45 PM
JRS
JRS - avatar
0
(E.g. you might be passing “1221” to the function but then you want to loop 4 times and not 1221 times!)
15th Feb 2022, 5:50 PM
JRS
JRS - avatar