在不使用额外的内存空间的条件下判断一个整数是否是回文。
回文指逆序和正序完全相同。
数据范围:
进阶: 空间复杂度
,时间复杂度
提示:
负整数可以是回文吗?(比如-1)
如果你在考虑将数字转化为字符串的话,请注意一下不能使用额外空间的限制
你可以将整数翻转。但是,如果你做过题目“反转数字”,你会知道将整数翻转可能会出现溢出的情况,你怎么处理这个问题?
int hi=0; while(x/hi>=10) hi*=10;
while(x!=0){
int left = x/hi;
int right = x%10;
if(left!=right) return false;
x=(x%hi)/10;
hi=hi/100;
}
主要思想就是每次将数字的第一位和最后一位进行对比。
如果不相等直接返回false,相等则将数字的第一位和最后一位去掉,重复以上流程。
public class Solution {
public boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
int div = 1;
while (x / div >= 10) {
div *= 10;
}
while (x > 0) {
int left = x / div;
int right = x % 10;
if (left != right) {
return false;
}
x = x % div / 10;
div /= 100;
}
return true;
}
}
class Solution: def isPalindrome(self , x: int) -> bool: # write code here return str(x)==str(x)[::-1]
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) return false;
int _x = x;
long int n = 0;
while (_x) {
n = (n << 1) + (n << 3) + _x % 10;
_x /= 10;
}
return n == x;
}
}; function isPalindrome( x ) {
// write code here
if(x>=0){ /// >=0的时候做整数反转 判断翻转后的数字是否和原数字相等
let res = 0,a = x
while(a!==0){
res = res*10 + a% 10
a = (a/10) |0
}
(res|0) === res? res : 0
return res == x ? true : false
}
return false //小于0 肯定不是回文数字
} bool isPalindrome(int x) {
// 若为负数,则不能为回文
// 若为0,则是回文
if (x <= 0) return x == 0;
// 先求出位数,之后前后比较
int digits = 0, num = x;
while (num != 0) {
digits ++; num /= 10;
}
while (digits > 1) { // 比较第一个和最后一个数字
int first = x / pow(10, digits - 1);
int last = x % 10;
if (first != last) return false;
x = (x - first * pow(10, digits - 1)) / 10;
digits -= 2;
}
return true;
}
直接求解法
public boolean isPalindrome(int x) {
if (x < 10) return x >= 0;
int base = 1;
for (int i = x; i > 9; base *= 10, i /= 10);
for (;x > 0 && base > 0; base /= 100) {
int head = x / base, tail = x % 10;
if (head != tail) return false;
x %= base;//掐头
x /= 10;//去尾
}
return true;
}