【LeetCode】13.Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

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.

负数都不是回文数。判断回文数首先想到的是hints中的两个做法。分别用两种做法试了下,都A了,不知道是不是判定系统有没有考虑the restriction of using extra space。

下面三种方法第三种最快。

1、转换为字符串 java 1304 ms

public class Solution {
    public boolean isPalindrome(int x) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        String num = String.valueOf(x);
        return new StringBuffer(num).reverse().toString().equalsIgnoreCase(num);
    }
}

2、Reverse Integer   cpp 328 ms  java 1340 ms

public class Solution {
    public boolean isPalindrome(int x) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int temp = x,n=0;
        if (x < 0)
            return false;
        if (x == 0)
            return true;
        while (temp>0)
        {
            n = n*10+temp%10;
            temp = temp/10;
        }
        return (x == n);
    }
}

 注意:java中不能写while (temp),会出现编译错误,C++可以。

3、最左最右逐位比较 cpp 268 ms  java 1180ms  

public class Solution {
    public boolean isPalindrome(int x) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int temp = x,n=0;
        if (x < 0)
            return false;
        if (x == 0)
            return true;
        int base=1;
        while(x/base>=10) 
            base*=10;
        while(x>0){
            int left=x/base;
            int right=x%10;
            if(left!=right)
                return false;
            x-=base*left;
            x/=10;
            base/=100;
        }
        return true;
    }
}

  

原文地址:https://www.cnblogs.com/guozhiguoli/p/3373720.html