LeetCode刷题day010 (Jieky)

LeetCode第9题

/*
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:
Input: 121
Output: true

Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:
Coud you solve it without converting the integer to a string?
*/
public class PalindromeNumber{
     
	
	// 数组倒置后可能超过int范围。①任意 逆序后超过int范围的数,不是回文数。???
	// 使用反正法:②存在 逆序后超过int范围的数,是回文数。(若是错的,表示上面的成立)
	/*
	MAX = 2147483647
	若有3*********,则原数据为3********3 > 2147483647,不存这种情况
	若有22********,则原数据为22******22 > 2147483647,不存这种情况
	若有215*******,则原数据为215****512 > 2147483647,不存这种情况
	若有2148******,则原数据为2148**8412 > 2147483647,不存这种情况
	若有21475*****,则原数据为2147557412 > 2147483647,不存这种情况
	
	有:214744****,则原数据为2147447421 < 2147483647,所以②不成立,那么①成立
	*/ 
	
	public static void main(String[] args){
     
		
		PalindromeNumber pn = new PalindromeNumber();
		boolean result = pn.reverse(10);
		System.out.println(result);
		System.out.println(Integer.MAX_VALUE);
	}
	
	public boolean reverse(int x){
     
		// 负数不是回文数
		if (x < 0) return false;
		
		int temp = x;
		int ret = 0;
		while(temp != 0){
     
			// 逆序溢出的数不是回文数
			if (ret > Integer.MAX_VALUE/10) return false;
			ret = ret*10 + temp%10;
			temp = temp/10; 
		}
		
		return ret == x ? true:false;
	}
}

你可能感兴趣的:(LeetCode,java,leetcode)