题目:Determine whether an integer is a palindrome. Do this without extra space.
翻译:判断一个数字是否是回文数,不要额外空间。
解题思路:因为数字既然传过去了,就不会有越界的问题。每次只需要取最前面和最后面的那一位数字进行比较,相同则继续,不同则返回、
首先要获取数字的位数,假设数字是12344321,一共有8位。
其次是要每次取前后各一位来进行比较,用数字除以1后面7个0得到第一位,用数字对10取余数得到最后一位。
此时要比较第二位和倒数第二位,只需将数字对1后面7个0取余后,在除以10.这样数字就变为234432,然后再把位数除以100。循环可得到结果。
public class Solution {
public static boolean isPalindrome(int x) {
if(x <0) return false;
int length = 1;//数字的位数
while(x/10 >= length)
{
length *=10;
}
while(x>0)
{
int high = x /length;
int low = x % 10;
if(high != low)
return false;
x = (x%length)/10;
length = length /100;
}
return true;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成的方法存根
int x = 1234554321;
boolean t = isPalindrome(x);
System.out.println(t);
}
}
做完后,查看别人的做法,发现有个不错的。采用的是递归,
粘在这里,方便以后复习用、
代码2:http://blog.csdn.net/ithomer/article/details/8798274
bool check(int x, int &y) {
if (x == 0) return true;
if (check(x/10, y) && (x%10 == y%10)) {
y /= 10;
return true;
} else {
return false;
}
}
bool isPalindrome(int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(x < 0) return false;
return check(x, x);
}