不使用数学怎么知道数字是否是回文?

时间:2019-01-18 22:57:56

标签: c++

所以我在考虑是否可以使用字符串来检查数字是否是回文,但是我真的不知道字符串,数组和这些东西是如何工作的,我什么都没得到。

我已经使用数学完成了此操作,但我想知道使用数组或字符串是否会更容易。

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

这是用数学编写的代码

所以可以,但是我很好奇

2 个答案:

答案 0 :(得分:1)

如果在循环中正确使用数组的索引,则容易得多:

// 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

答案 1 :(得分:0)

使用此代码:-

//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.";