Leetcode09.回文数

一、题目

给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。

回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。

                           示例 1:

输入:x = 121 输出:true

                            示例 2:

输入:x = -121 输出:false 解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。

                            示例 3:

输入:x = 10 输出:false 解释:从右向左读, 为 01 。因此它不是一个回文数。

                           示例 4:

输入:x = -101 输出:false

提示:

-231 <= x <= 231 - 1

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、代码

1.方法1

class Solution {
    
    
    public boolean isPalindrome(int x) {
    
    
    if(x<0)return false;
    if(x/10==0)return true;
    int ans=x;
	int res=0;
	while(x>0) {
    
    
		int temp=x%10;
		if(res>Integer.MAX_VALUE||(res==Integer.MAX_VALUE&&temp>7)) 
			return false;
		x/=10;
		res=res*10+temp;
	}
	return res==ans?true:false;
    }
}

2、方法2

//下面代码虽然非常简简洁,但是无论是时间还是空间性能都远不如方法1

class Solution {
    
    
    public boolean isPalindrome(int x) {
    
    
	String s=x+"";
	for (int i = 0,j=s.length()-1; i < j; i++,j--) {
    
    
		if(s.charAt(i)!=s.charAt(j))
		return false;
	}
	return true;
    }
}

3、官方答案

个人感觉这个答案非常好,所以把他贴了过来,if里加了多个判断语句,避免了多次if去判断,而且处理溢出的方式也非常奈斯,官方选择了while(x>revertedNumber)这个循环,这样时间复杂度是n/2,不仅比方法1中的代码简洁,而且时间性能也更好。

class Solution {
    
    
    public boolean isPalindrome(int x) {
    
    
        if (x < 0 || (x % 10 == 0 && x != 0)) {
    
    
            return false;
        }
        int revertedNumber = 0;
        while (x > revertedNumber) {
    
    
            revertedNumber = revertedNumber * 10 + x % 10;
            x /= 10;
        }
        return x == revertedNumber || x == revertedNumber / 10;
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/palindrome-number/solution/hui-wen-shu-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

猜你喜欢

转载自blog.csdn.net/m0_51801058/article/details/114106564