判断是否是回文数字
(牛客网—牛客题霸算法篇—NC56)
题目描述
在不使用额外的内存空间的条件下判断一个整数是否是回文。
回文指逆序和正序完全相同
默认负数不是回文数
思路
Java实现
如果考虑将数字转化为字符串的话,需要使用额外空间的限制
考虑将整数翻转,但要注意溢出的情况,具体处理见反转数字
代码实现
import java.util.*;
public class Solution {
/**
*
* @param x int整型
* @return bool布尔型
*/
public int reverse (int x) {
// write code here
long y=0;//防止溢出
while(x!=0){
y=y*10+x%10;
x=x/10;
}
return (int)y==y?(int)y:0;
}
public boolean isPalindrome (int x) {
// write code here
if(x==0)
return true;
if(x<0)
return false;
int y=reverse(x);
if(x==y)
return true;
return false;
}
}