参考:leetcode num:009
package num009;
import java.util.Scanner;
public class Num009Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
Solution num009 = new Solution();
boolean B = num009.isPalindrome01(x);
boolean C = num009.isPalindrome02(x);
boolean D = num009.isPalindrome03(x);
boolean E = num009.isPalindrome04(x);
System.out.println(E);
}
}
class Solution {
public boolean isPalindrome01(int x) {
//转换为字符转,字符串翻转和比较
String str1 = new StringBuilder(x+"").reverse().toString();
String str2 = x + "";
return str1.equalsIgnoreCase(str2);
}
public boolean isPalindrome02(int x) {
//将整数的个位与最高位、十位与正数第二位、等等依次进行比较
if((x/10)>0){
int i = 0;
int y = x;
while((y/10)>0){i=i+1;y=y/10;}
int left = 0;
int right = 0;
for(int j = 0; (2*j)<i;j++){
if(left == right){
left = x/(10^(i-j));
right = x%(10^(j+1));
}else{
return false;
}
}
return true;
}else{
return x > 0;
}
}
public boolean isPalindrome03(int x) {
//将整数整体翻转后,与原始数据进行比较
int newrevers = 0 ;
int y = x;
if(x/10>0){
while(x/10>0){
newrevers = newrevers*10 + x%10;
x = x/10;
}
return newrevers==(y/10);
}else {
return x>0;
}
}
public boolean isPalindrome04(int x) {
//在03算法基础上采用折中对比
if(x<0){
return false;
}
int newrever = 0;
while(x>newrever){
newrever = newrever*10+(x%10);
x = x/10;
}
return x == newrever || x==newrever/10;
}
}