问题描述:
Determine whether an integer is a palindrome. Do this without extra space.
中文大意:
判断一个数是不是回文数,注意不能用额外空间。
解题思路:
1.变成字符串比较。但是不能用额外空间,此处不可行。
2.反转数字后比较。参照L007_Reverse_Integer,我们知道反转后的数值可能超出范围,故不可行。
3.每次取出最高位和最低位比较。
代码:
package LeetCode;
import java.util.Scanner;
public class L009_Palindrome_Number {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = in.nextInt();
L009_Palindrome_Number pn = new L009_Palindrome_Number();
System.out.println(pn.isPalindrome(x));
}
public boolean isPalindrome(int x){
if(x<0)
return false;
int whole = 1;//whole为10^n,用来取出x的最高位。eg:x=12321,则whole=10000。
while(x/whole>=10)
whole *= 10;
while(x>0){
int left = x/whole;
int right = x%10;
if(left!=right)
return false;
else{
//x去头去尾
x -= whole*left;
x /= 10;
whole /=100;//因为去掉了两位数,whole要除以100
}
}
return true;
}
}