**题目描述:**判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例1:
输入:121
输出:true
示例2:
输入:-121
输出:false
示例3:
输入:10
输出:false
注:考虑不将整数转为字符串来解决这个问题。
代码:(C++)
#include<stdio.h>
#include<iostream>
#include<cmath>
using namespace std;
bool isPalindrome(int x);
int main() {
int x;
cin >> x;
isPalindrome(x);
system("pause");
return 0;
}
bool isPalindrome(int x) {
int count = 0;
while (pow(10, count)<x) {
count++;
}
int high = 0;
int low = 0;
for (int i = 1; i<=count / 2; i++) {
high = x / pow(10, count - 2 * i + 1);//取最高位
low = x % 10;//取最低位
if (high != low) {
cout << "false" << endl;
return false;
}
x = (x - high*pow(10, count - 2 * i + 1)) / 10;//对x值进行更新
}
cout << "true" << endl;
return true;
}
运行结果: