Palindrome Number

题目描述
Determine whether an integer is a palindrome. Do this without extra space.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

解题思路
本题主要的问题是需要使用O(1)的空间复杂度,因此不能使用转换为字符串的方式做。并且在解题中需要注意一些非常特殊的情况,在代码中已经标出。

相关知识点
(1)Java中int的取值范围
四个字节,-2147483648~2147483647( 一共10位

自己的代码
package leetcode;

public class PalindromeNumber {
	public boolean isPalindrome(int x) {
		if(x < 0) return false;
		if(x >= 0 && x <= 9) return true;
		if( x >= 10 && x <=99){
			if(x/10 == x%10) return true;
			else return false;
		}
		int bigBase = 100;
		int smallBase = 10;
		while(true){
			if(x < bigBase){
				bigBase /= 10;
				break;
			}
			bigBase *= 10;
			//处理整数越界
			if(bigBase == 1000000000) break;
		}
		boolean palindrome = true;
		while(x >= 100){
			int high = x/bigBase;
			int low = x%smallBase;
			if(high != low) {
				palindrome = false;
				break;
			}
			x = (x - high*bigBase - low)/10;
			bigBase /= 100;
		}
		
		//还要处理100021这种特殊情况
		if(bigBase > 100) {
			//处理100001这种情况
			if(x == 0) return true;
			return false;
		}

		if( x >= 10 && x <=99){
			if(x/10 != x%10) palindrome =false;
		}
		
        return palindrome;
    }
	
	public static void main(String[] args) {
		//int x= 0;
		//int x= 12;
		//int x= 11;
		//int x= 123;
		//int x= 121;
		//int x= 1221;
		//int x= 1234;
		//int x= 12321;
		//int x= 12211;
		//int x= 123321;
		//int x= 122113;
		//int x= 1874994781;
		//int x = 1000021;
		int x = 1000001;
		
		PalindromeNumber pn = new PalindromeNumber();
		System.out.println(pn.isPalindrome(x));
	}
}

你可能感兴趣的:(number)