1

So I'm thinking if I could use strings to check if a number is a palindrome, but I don't really know how strings, arrays and that stuff works and I'm not arriving at anything.

I've done this using math, but I wonder if it would be easier to use arrays or strings.

n = num;
 while (num > 0)
 {
      dig = num % 10;
      rev = rev * 10 + dig;
      num = num / 10;
 }
// If (n == rev) the number is a palindrome

this is the code made with math

So it works yeah, but I'm curious

iggykimi
  • 129
  • 4
  • 3
    Related: [Check if a string is palindrome](https://stackoverflow.com/questions/8362572/) – Remy Lebeau Jan 18 '19 at 22:59
  • If you already have a number converting the number to a `string` will cost more than you will likely save. Also note: you only have to go half way when testing palindromes. If you have a palindrome, the second half is identical to the first half, which you should have have already tested. If it's not a palindrome, you should have already exited the loop. – user4581301 Jan 18 '19 at 23:02
  • @RemyLebeau [which is itself a duplicate](https://stackoverflow.com/questions/3285432/to-find-if-a-given-string-is-palindrome-or-is-not-palindrome) – chb Jan 19 '19 at 00:00
  • @chb yes, I know. They both provide answers, so I linked to the duplicate, which then links to another duplicate. That way, the OP can see more answers. – Remy Lebeau Jan 19 '19 at 00:21
  • @RemyLebeau Did you flag the question? And, if so, why did you choose to rephrase the automatically generated text to "Related"? – chb Jan 19 '19 at 02:33
  • @chb no, I did not flag it. I wrote "Related", it was not auto generated. – Remy Lebeau Jan 19 '19 at 06:19
  • The "Answer" to this downvoted question may help: [How to understand this C++ palindrome code?](https://stackoverflow.com/questions/44400246/how-to-understand-this-c-palindrome-code) – David C. Rankin Jan 19 '19 at 08:31

2 Answers2

1

It is much easier if you use correctly the index of the array in the loop:

// Num is the number to check
// Supposing we are using namespace std
string numString = to_string(num);
bool palindrome = true;
int index = 0;
while(index < numString.size() && palindrome){
   palindrome = numString[index] == numString[numString.size() - index - 1];
   index++;
}
if(palindrome)
   cout << num << " is a palindrome \n"; // line break included
else
   cout << num << " is not a palindrome \n"; // line break included
Inma
  • 11
  • 3
0

Use this code:-

//num is the Number to check
//Converting int to String
ostringstream ss;
ss<<num;
string snum = ss.str();
string fromfront="", fromback="";
fromfront = snum;
string character;
for(int i=snum.length();i>0;i--)
{
    if(i>0)
        character = snum.substr(i-1, 1);
    fromback+=character;
}
if(fromfront==fromback)
    cout<<endl<<"It is a palindrome.";
else
    cout<<endl<<"It is not a palindrome.";
GameChanger
  • 179
  • 11