判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例 1:
输入: 121
输出: true
示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。
进阶:
你能不将整数转为字符串来解决这个问题吗?
由于这道题本身较容易,因此直接考虑进阶方法。
我采用的是先确定最高位位数,然后从两头向中心判断是否回文
取第n位数字的方法是 (完整数字 / 10^n) % 10
完整代码:
#include<vector>
#include<ctype.h>
#include<stdio.h>
#include<cstdio>
#include<string>
#include<iostream>
using namespace std;
bool isPalindrome(int x) {
cout <<"num:" << x << endl;
if(x < 0){
return false;
}
int left_p = 1,right_p = 1;
while(left_p <= x / 10){
left_p *= 10;
}
// cout << left_p << endl;
while(left_p >= right_p){
// cout << (x / left_p)% 10 << " " << (x / right_p)% 10 << endl;
if((x / left_p)% 10 != (x / right_p)% 10){
return false;
}
right_p *= 10;
left_p /= 10;
}
return true;
}
int main(){
cout << isPalindrome(-2147483648) << endl;
cout << isPalindrome(-10) << endl;
cout << isPalindrome(-5) << endl;
cout << isPalindrome(0) << endl;
cout << isPalindrome(1) << endl;
cout << isPalindrome(10) << endl;
cout << isPalindrome(101) << endl;
cout << isPalindrome(5005) << endl;
cout << isPalindrome(104401) << endl;
cout << isPalindrome(2147483647) << endl;
return 0;
}