可以将整数转换为字符串,然后再判断该字符串是否为回文串。
-
将整数转化为字符串,可以使用 to_string() 方法;
-
使用双指针法判断字符串是否为回文串。
#include <iostream>
#include <string>
using namespace std;
bool isPalindrome(int x) {
// 将整数转化为字符串
string s = to_string(x);
int left = 0, right = s.size() - 1;
// 使用双指针法判断字符串是否为回文串
while (left < right) {
if (s[left] != s[right]) {
return false;
}
left++;
right--;
}
return true;
}
int main() {
int x = 12321;
if (isPalindrome(x)) {
cout << x << " is a palindrome number." << endl;
} else {
cout << x << " is not a palindrome number." << endl;
}
return 0;
}
输出结果为:
12321 is a palindrome number.