【LeetCode】Palindrome Number

Palindrome Number 
Total Accepted: 13733 Total Submissions: 47166 My Submissions
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.
【解题思路】
转为字符串,一一比较是否相同。
可以加个判断,如果是负数,直接return false即可

Java AC

public class Solution {
    public boolean isPalindrome(int x) {
        String str = x + "";
        int len = str.length();
        if(len == 1){
            return true;
        }
        int i = 0;
        int j = len-1;
        while(i <= j && i < len && j >= 0){
            if(str.charAt(i) != str.charAt(j)){
                return false;
            }
            i++;
            j--;
        }
        return true;
    }
}

Python AC

class Solution:
    # @return a boolean
    def isPalindrome(self, x):
        xstr = str(x)
        xlen = len(xstr)
        if xlen == 1:
            return True
        i = 0
        j = xlen - 1
        while i <= j:
            if xstr[i] != xstr[j]:
                return False
            else:
                i += 1
                j -= 1
        return True


你可能感兴趣的:(【LeetCode】Palindrome Number)