C++ 如何不用数学就知道一个数字是否是回文?

C++ 如何不用数学就知道一个数字是否是回文?,c++,C++,所以我在想,我是否可以用字符串来检查一个数字是否是回文,但我真的不知道字符串、数组和那些东西是如何工作的,我什么都没有得到 我已经用数学完成了这项工作,但我想知道使用数组或字符串是否更容易 n = num; while (num > 0) { dig = num % 10; rev = rev * 10 + dig; num = num / 10; } // If (n == rev) the number is a palindrome 这是用

所以我在想,我是否可以用字符串来检查一个数字是否是回文,但我真的不知道字符串、数组和那些东西是如何工作的,我什么都没有得到

我已经用数学完成了这项工作,但我想知道使用数组或字符串是否更容易

n = num;
 while (num > 0)
 {
      dig = num % 10;
      rev = rev * 10 + dig;
      num = num / 10;
 }
// If (n == rev) the number is a palindrome
这是用数学编写的代码

是的,但我很好奇使用以下代码:-

//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.";
//num是要检查的数字
//将int转换为字符串
ostringstream ss;
ss0)
字符=snum.substr(i-1,1);
fromback+=字符;
}
if(fromfront==fromback)

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

// 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
//Num是要检查的数字
//假设我们使用的是名称空间std
字符串numString=to_字符串(num);
布尔回文=真;
int指数=0;
while(索引cout-Related:如果您已经有一个号码,那么将该号码转换为
字符串将花费比您可能节省的更多的费用。还要注意:在测试回文时,只需做一半。如果您有回文,那么后半部分与前半部分相同,您应该已经测试过了。如果不是回文,你应该已经退出循环了。@RemyLebeau@chb是的,我知道。它们都提供了答案,所以我链接到副本,然后再链接到另一个副本。这样,OP可以看到更多的答案。@RemyLebeau你标记了这个问题吗?如果是这样,为什么选择将自动生成的文本重新表述为“相关”?