9. Palindrome Number 回文数

题目: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?

题意解析:

确定整数是否是回文,当一个整数向后读取与向前读取的内容相同时,它就是一个回文。

解题思路一:

几乎所有人都能想到的就是将整数转换成字符串,然后对字符串进行判断即可。

public boolean isPalindrome(int x) {
        String s = String.valueOf(x);
        int i=0,j = s.length()-1;
        while (i<=s.length()-1 && j >= 0){
            if (s.charAt(i) != s.charAt(j)){
                return  false;
            }
            i++;
            j--;
            if (i >= j){
                return true;
            }
        }

        return true;
    }

此算法时间复杂度O(n/2)

提交代码之后:

Runtime: 8 ms, faster than 99.62% of Java online submissions for Palindrome Number.

Memory Usage: 34.8 MB, less than 100.00% of Java online submissions for Palindrome Number.

解题思路二:

不做字符转换,在原地进行判断,定义一个整数y,从x的个位数依次向前取数,每次取一个新的数字时,就将y当前的数值扩大10倍再加上需要相加的数字,直到 y >= x即结束。将我们的整数分为前后两部分,那么当整数的位数为奇数时,后面的部分除以10跟前面相等,

如12321,前面 12后面123。当个数为偶数时,前面的整数跟后面相等,如1221,前面12,后面12

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

        return x == y || x == y / 10 ? true : false;
    }

此算法时间复杂度也是O(n/2),不过胜在没有做字符串的转换。

提交代码之后,

Runtime: 6 ms, faster than 100.00% of Java online submissions for Palindrome Number.

Memory Usage: 34.4 MB, less than 100.00% of Java online submissions for Palindrome Number.

猜你喜欢

转载自blog.csdn.net/qq_21963133/article/details/88861600
今日推荐