1.回文数概念
"回文"是指正读反读都能读通的句子,它是古今中外都有的一种修辞方式和文字游戏,如"我为人人,人人为我"等。在数学中也有这样一类数字有这样的特征,称为回文数(palindrome number)。
设n是一任意自然数。若将n的各位数字反向排列所得自然数n1与n相等,则称n为一回文数。例如,若n=1234321,则称n为一回文数;但若n=1234567,则n不是回文数。
注意:
1.偶数个的数字也有回文数124421
2.小数没有回文数
示例1:
输入:aba
输出:true
示例二:
输入:hello
输出:false
2.代码实现
package test;
/**
* @author WuChenGuang
*/
public class Test01 {
public static void main(String[] args) {
/*
回文数据
需求:通过上面以数组模拟栈来判断一个字符串是否是一个回文数据
*/
System.out.println("hello" + (detecation("hello") ? "是回文数" : "不是回文数"));
System.out.println("aba" + (detecation("aba") ? "是回文数" : "不是回文数"));
}
/**
* 判断一个字符串是否是一个回文数据
*/
public static boolean detecation(String val) {
// 初始化栈对象
Test01 arrayStack = new Test01(10);
// 获取字符串长度
int length = val.length();
// 把字符串数据逐次获取字符压栈至数组中
for (int i = 0; i < length; i++) {
arrayStack.push(val.charAt(i));
}
// 弹栈
StringBuilder newVal = new StringBuilder();
int length1 = arrayStack.length();
for (int i = 0; i < length1; i++) {
// 判断是否是一个空栈
if (!arrayStack.isEmpty()) {
char pop = (char) arrayStack.pop();
newVal.append(pop);
}
}
return val.equals(newVal.toString());
}
// 栈的大小
private int maxStack;
// 数组用来模拟栈
private int[] stack;
// 表示栈顶所在的位置,默认情况下如果没有数据时,使用-1
private int top = -1;
public Test01(int maxStack) {
this.maxStack = maxStack;
stack = new int[maxStack];
}
/**
* 判断是否已经满栈
*/
public boolean isFull() {
return this.top == this.maxStack - 1;
}
/**
* 判断栈是否是空栈
*/
public boolean isEmpty() {
return this.top == -1;
}
/**
* 压栈
*/
public void push(int val) {
// 判断是否已经栈满
if (isFull()) {
throw new RuntimeException("此栈已满");
}
// System.out.println(val + "入栈了");
top++;
stack[top] = val;
}
/**
* 弹栈
*/
public int pop() {
// 如果栈中是空
if (isEmpty()) {
throw new RuntimeException("空栈,未找到数据");
}
int value = stack[top];
top--;
return value;
}
/**
* 查看栈中所有元素
*/
public void list() {
// 判断是否是空栈
if (isEmpty()) {
throw new RuntimeException("空栈,未找到数据");
}
for (int i = 0; i < stack.length; i++) {
System.out.printf("stack[%d]=%d\n", i, stack[i]);
}
}
/**
* 栈中元素存在的个数
*/
public int length() {
return this.top + 1;
}
}
运行结果: