编程题目:
50.输入一个5位数,判断它是不是回文数。例如:12321是回文数,个位与万位相同,十位与千位相同。
示例代码:
package program.calculation.exercise50;
import java.util.Scanner;
/**
* 50.输入一个5位数,判断它是不是回文数。
* 例如:12321是回文数,个位与万位相同,十位与千位相同。
*/
public class PalindromicNumber {
public static void main(String[] args) {
System.out.println("请输入一个5位数:");
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
System.out.println("第一种方式:");
if(isPalindromicNumber1(number)) {
System.out.println(number+"是回文数!");
}else {
System.out.println(number+"不是回文数!");
}
System.out.println("第二种方式:");
if(isPalindromicNumber2(number)) {
System.out.println(number+"是回文数!");
}else {
System.out.println(number+"不是回文数!");
}
}
//第一种方式:判断是否是回文数
private static boolean isPalindromicNumber1(int number) {
String str = Integer.toString(number);
char[] cs = str.toCharArray();
if(cs[0] == cs[cs.length-1]){
if(cs[1] == cs[cs.length-2]){
return true;
}
}
return false;
}
//第二种方式:判断是否是回文数
private static boolean isPalindromicNumber2(long number) {
int count = 0;
int[] numArr = new int[5];
do {
numArr[count] = (int)(number%10);
number /= 10;
count++;
}while(0 != number);
for (int i=0; i<count; i++) {
if(numArr[i] != numArr[--count]) {
return false;
}
}
return true;
}
}
结果显示: