LeetCode.9:Palindrome Number

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?

思路:我在写完代码之后才发现最后的Follow up,真是醉了,首先想到的办法就是follow up中提到的“将整数转换为string,然后逆置一下,判断是否相等”
代码如下:

package com.Ryan;

public class PalindromeNumber {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		PalindromeNumber palindromeNumber=new PalindromeNumber();
		int x=-121;
		System.out.println(palindromeNumber.isPalindrome(x));
	}
	
	public boolean isPalindrome(int x) {
        String s=String.valueOf(x);
        int length=s.length();
        String reverse = "";
        for (int i = 0; i < length; i++) {
        	reverse = s.charAt(i) + reverse;
        }
        System.out.println(reverse);
        if (s.equals(reverse)) {
			return true;
		}
        else {
			return false;
		}
	}
}

如果不将int转换为string的话也是可以的,思路差不多,一个数学公式可以解决

int rev=0;
rev=rev*10+x%10;
x=x/10;

这样也可以实现int的逆置,这里需要在代码一开始排一下雷,例如题目中提到的负号问题,代码如下:

package com.Ryan;

public class PalindromeNumber {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		PalindromeNumber palindromeNumber=new PalindromeNumber();
		int x=-121;
		System.out.println(palindromeNumber.isPalindrome(x));
	}
	
	public boolean isPalindrome(int x) {
		if (x<0) {
			return false;
		}
		int tmp=x;
		int rev=0;
		while (tmp!=0) {
			rev=rev*10+tmp%10;
			tmp=tmp/10;
		}
		if (rev==x) {
			return true;
		}
        else {
			return false;
		}
    }
}

猜你喜欢

转载自blog.csdn.net/qq_32350719/article/details/89242726