第一种,暴力解法
import java.util.Scanner;
import java.lang.Math;
import java.util.Stack;
public class Main{
public static void main(String args[]){
Scanner per=new Scanner(System.in);
while(per.hasNextInt()){
int n=per.nextInt();
Solution reader=new Solution();
boolean a=reader.isPalindrome(n);
if(a==false)
System.out.println("非回文数!");
else
System.out.println("回文数");
}
}
}
class Solution {
public boolean isPalindrome(int x) {
String a=""+x;//将整数转化为字符串
StringBuffer b=new StringBuffer(a);
//新建一个输入流对象,并将a的内容作为参数
return a.equals(b.reverse().toString());
/*reverse()方法是将一个输入流对象倒序输出,并利用toString方法
*将其转化为字符串内容,并利用equals()方法进行比较
* */
}
}
最暴力的方法,直接把这个整数转化为字符串,然后,利用java里面的reverse()方法,直接将字符创翻转。并且比较这两个字符串,如果两个字符串相等,那么就是这个数就是一个回文数。(还可以截取前半部分字符串和后半部分字符串,方法也差不多)
第二种,还是暴力解法
import java.util.Scanner;
import java.lang.Math;
import java.util.Stack;
public class Main{
public static void main(String args[]){
Scanner per=new Scanner(System.in);
while(per.hasNextInt()){
int n=per.nextInt();
Solution reader=new Solution();
boolean a=reader.isPalindrome(n);
if(a==false)
System.out.println("非回文数!");
else
System.out.println("回文数");
}
}
}
class Solution {
public boolean isPalindrome(int x) {
if(x<0)
return false;
else
{
if(x==0)
return true;
else
{
String h=""+x;
char a,b;
int result=0;
//进行
for(int i=0;i<h.length()/2;++i)
{
a=h.charAt(i);
b=h.charAt(h.length()-1-i);
if(a!=b)
{
++result;
break;
}
}
if(result>0)
return false;
else
return true;
}
}
}
}
负数翻转肯定不是回文数,0反转就是回文数。对于正整数而言,将其转化为字符串。并且从遍历一半的位数,将第一个数转化为资产和最后一个位的数字转化为子簇,将第二个位数转化为字符和倒数第二个位置的数转化为字符,依次类推,一一比对,如果出现了不同,result便自增,然后跳出循环。
第三种解法,用纯数学的方法来做题。可以利用一个栈,存储数字的前半部分每个数字压进去栈中,然后,再将栈中的每个数字都一一弹出来,与后半部分的每个数字进行一一比对,如果出现了不同,那就直接结束循环。判断方法,与第二个方法的判断类似。
import java.util.Scanner;
import java.lang.Math;
import java.util.Stack;
public class Main{
public static void main(String args[]){
Scanner per=new Scanner(System.in);
while(per.hasNextInt()){
int n=per.nextInt();
Solution reader=new Solution();
boolean a=reader.isPalindrome(n);
if(a==false)
System.out.println("非回文数!");
else
System.out.println("回文数");
}
}
}
class Solution {
public boolean isPalindrome(int x) {
if(x<0)
return false;
else
{
if(x==0)
return true;
else
{
int k=0;//存储x的位数
int tmp=x;
while(tmp>0)
{
tmp=tmp/10;
++k;
}
int g=k/2;//需要取出的位数
Stack <Integer>stack=new <Integer> Stack();
//新建一个整型栈
int result=0;//判断器,如果有不等于的两个数字,即可以利用
//这个来作出判断
for(int i=0;i<g;++i)
{
stack.push((x/(int)Math.pow(10, k-i-1))%10);
/*因为上面判断出位数了,将这个整数的前半部分数字
* 压进栈中*/
}
x=x%(int)Math.pow(10, g);
//将压入栈中的前半部分数字给消去,虽然位数会有奇偶位数之分,不过不影响
for(int i=0;i<g;++i)
{
if(stack.pop()!=(x/(int)Math.pow(10, g-i-1)%10))
{//将后半部分的数字逐一弹出比对,一有不同,结束栈
++result;
break;
}
}
if(result>0)
return false;
else
return true;
}
}
}
}