Is there any way to simplify Palindrome Numbers coding? | Sololearn: Learn to code for FREE!

+1

Is there any way to simplify Palindrome Numbers coding?

this is my code for Palindrome Numbers and I'm wondering if there's anyway to improve or simplify #include <iostream> using namespace std; bool isPalindrome(int x) { //complete the function //define variables int arrsize=1; int j=x; int l=x; int m; int o; //feaguring arrsize while(j/10>=1){ j /= 10; arrsize++; } //put single integer into array int arr[arrsize]; for(int k=0;k<arrsize;k++){ m = l%10; arr[k]=m; l/=10; } //check if it's palindrome for(int n=0;arrsize>n;n++){ if(arr[n]==arr[arrsize-1-n]){ } else return false; } return true; } //remain as the question int main() { int n; cin >>n; if(isPalindrome(n)) { cout <<n<<" is a palindrome"; } else { cout << n<<" is NOT a palindrome"; } return 0; }

7/24/2021 3:14:54 PM

嘎五

5 Answers

New Answer

+2

Jazz the isPalindrome() function is an exercise in the C++ course. The integer value is passed to the function. Just use std::to_string() to convert the integer to a string; duplicate the string, reverse the duplicate and compare the two strings. If the two strings are equal then the number is a palindrome and return true, otherwise return false.

+1

Big Thanks for all the answers above, I'll review the Conditional Operator and try to simplify my code.

0

#include <iostream> using namespace std; bool isPalindrome(int reverse, int check) { bool status = true; if (reverse != check) { status = false; } return status; } int main() { int n, reverse = 0, rem; cin >> n; int check = n; while(n != 0){ rem = n % 10; reverse = reverse * 10 + rem; n /= 10; } if(isPalindrome(reverse, check) == 1) { cout << reverse <<" is a palindrome"; } else { cout << check <<" is NOT a palindrome"; } return 0; }