Determine whether an integer is a palindrome. Do this without extra space.
“回文”是指正读反读都能读通的句子,它是古今中外都有的一种修辞方式和文字游戏,如“我为人人,人人为我”等。在数学中也有这样一类数字有这样的特征,成为回文数(palindrome number)。
设n是一任意自然数。若将n的各位数字反向排列所得自然数n1与n相等,则称n为一回文数。例如,若n=1234321,则称n为一回文数;但若n=1234567,则n不是回文数。
注意:
“回文”是指正读反读都能读通的句子,它是古今中外都有的一种修辞方式和文字游戏,如“我为人人,人人为我”等。在数学中也有这样一类数字有这样的特征,成为回文数(palindrome number)。
设n是一任意自然数。若将n的各位数字反向排列所得自然数n1与n相等,则称n为一回文数。例如,若n=1234321,则称n为一回文数;但若n=1234567,则n不是回文数。
注意:
1.偶数个的数字也有回文数124421
2.小数没有回文数
针对此题,我使用相对麻烦的方法。。。 时间复杂度想都不要想了。。。 稍后会更新O(1)的算法代码,原始代码如下:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by jason on 2016/1/6.
*/
class Solution36 {
boolean bool;
public boolean isPalindrome(int x) {
if(x/10 == 0 && x>=0) {
return true;
}
if(x > -10 && x<0) {
return false;
}
String xtoString = String.valueOf(x);
String oneString = xtoString.substring(0, xtoString.length()/2);
String twoString = xtoString.substring(xtoString.length()/2);
StringBuilder sb = new StringBuilder();
sb.append(twoString);
sb.reverse();
char[] xTochar1 = oneString.toCharArray();
char[] xTocahr2 = sb.toString().toCharArray();
List<Character> aList = new ArrayList<Character>();
List<Character> bList = new ArrayList<Character>();
for(int i=0; i<xTochar1.length; i++) {
aList.add(xTochar1[i]);
}
for(int j=0; j<xTocahr2.length; j++) {
bList.add(xTocahr2[j]);
}
if(aList.size() != bList.size()) {
bList.remove(xTocahr2.length-1);
}
String aListString = aList.toString();
String bListString = bList.toString();
if(aListString.equals(bListString)) {
bool = true;
}else {
bool = false;
}
if(bool) {
return true;
}else {
return false;
}
}
}
public class LC36 {
public static void main(String[] args) {
Solution36 solution36 = new Solution36();
if(solution36.isPalindrome(1000021)) {
System.out.println("true");
}else {
System.out.println("false");
}
}
}
优化的代码来了!!! 如下所示:
/**
* Created by jason on 2016/1/6.
*/
class Solution37 {
public boolean isPalindrome(int x) {
if(x<0) {
return false;
}
return x == reverse(x);
}
public int reverse(int n) {
int rst=0;
while (n != 0) {
rst = rst*10 + n%10;
n = n/10;
}
return rst;
}
}
public class LC37 {
public static void main(String[] args) {
Solution37 solution37 = new Solution37();
if(solution37.isPalindrome(1000121)) {
System.out.println("true");
}else {
System.out.println("false");
}
}
}