详细见:leetcode.com/problems/palindrome-number/
Java Solution: github
package leetcode;
public class P009_PalindromeNumber {
public static void main(String[] args) {
// System.out.println(Integer.MAX_VALUE);
System.out.println(new Solution3().isPalindrome(1221));
}
/*
* 16 ms
* 20.14%
*
*/
static class Solution {
public boolean isPalindrome(int x) {
char[] c = String.valueOf(x).toCharArray();
int sta = 0, end = c.length - 1;
while (sta < end) {
if (c[sta] == c[end]) {
sta ++;
end --;
} else {
return false;
}
}
return true;
}
}
/*
* 14 ms
* 26.79%
*/
static class Solution2 {
public boolean isPalindrome(int x) {
if (x < 0)
return false;
int[] c = new int[x == 0 ? 1 : (int)Math.log10(x) + 1];
for (int i = c.length - 1; i > -1; i --) {
c[i] = x % 10;
x = x / 10;
}
int sta = 0, end = c.length - 1;
while (sta < end) {
if (c[sta] == c[end]) {
sta ++;
end --;
} else {
return false;
}
}
return true;
}
}
/*
* 75.99%
* 11 ms
*/
static class Solution3 {
public boolean isPalindrome(int x) {
if (x < 0)
return false;
int[] c = new int[10];
int i = 9;
for (; i > -1; i --) {
c[i] = x % 10;
x = x / 10;
if (x == 0)
break;
}
int sta = i, end = 9;
while (sta < end) {
if (c[sta] == c[end]) {
sta ++;
end --;
} else {
return false;
}
}
return true;
}
}
}
C Solution: github
/*
url: leetcode.com/problems/palindrome-number/
*/
#include <stdio.h>
#include <stdlib.h>
#define bool int
#define false 0
#define true 1
bool isPalindrome(int x) {
int arr[14];
int i = 0;
int j = 0;
int v = 0;
int xx = x;
if (x < 0) return false;
while (x != 0) {
arr[i ++] = x % 10;
x = x / 10;
}
for (j = 0; j < i; j ++) {
v = v * 10 + arr[j];
}
return xx == v;
}
int main() {
printf("%d\r\n", isPalindrome(6666));
return 0;
}
Python Solution: github
#coding=utf-8
'''
url: leetcode.com/problems/palindrome-number/
@author: zxwtry
@email: zxwtry@qq.com
@date: 2017年3月27日
@details: Solution: AC 249ms 56.14%
'''
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0: return False
v = x
c = 0
lst = []
while v != 0:
lst.append(v % 10)
v //= 10
c += 1
l,r = c -1,0
while l > r:
if lst[l] != lst[r]:
return False
l -= 1
r += 1
return True
if __name__ == "__main__":
x = -0
sol = Solution()
print(sol.isPalindrome(x))