1. 程式人生 > >Java演算法題目:一個5位數,判斷它是不是迴文數。即12321是迴文數,個位與萬位相同,十位與千位相同。

Java演算法題目:一個5位數,判斷它是不是迴文數。即12321是迴文數,個位與萬位相同,十位與千位相同。

題目:一個5位數,判斷它是不是迴文數。即12321是迴文數,個位與萬位相同,十位與千位相同。

網上的結果如下:

import java.util.Scanner;
public class Ex25 {
static int[] a = new int[5];
static int[] b = new int[5];
public static void main(String[] args) {
   boolean is =false;
   Scanner s = new Scanner(System.in);
   long l = s.nextLong();
   if (l > 99999 || l < 10000) {
    System.out.println("Input error, please input again!");
    l = s.nextLong();
   }
   for (int i = 4; i >= 0; i--) {
    a[i] = (int) (l / (long) Math.pow(10, i));
    l =(l % ( long) Math.pow(10, i));
   }
   System.out.println();
   for(int i=0,j=0; i<5; i++, j++) {
     b[j] = a[i];
   }
   for(int i=0,j=4; i<5; i++, j--) {
    if(a[i] != b[j]) {
     is = false;
     break;
    } else {
     is = true;
    }
   }
   if(is == false) {
    System.out.println("is not a Palindrom!");
   } else if(is == true) {
    System.out.println("is a Palindrom!");
   }
}
}

我自己修改了一下,不僅僅是數字,字串也可以判斷的
Scanner ax= new Scanner(System.in);
		String s = ax.next();
		System.out.println(s.length());

		char[] ch=s.toCharArray();
		
		if ((s.length()%2)==0){
			for (int i=0;i<=s.length()/2-1;i++){
				char current=ch[i];
				char cupple=ch[(s.length()-1-i)];
				if (current==cupple){
					System.out.println("第 "+i + "輪");
					System.out.println("值為: " + current);
					System.out.println("對應的值為:" + cupple);			
				}
			}
		}else{
			for (int i=0;i<=(s.length()-1)/2-1;i++){
				char current=ch[i];
				char cupple=ch[(s.length()-1-i)];
				if (current==cupple){
					System.out.println("第 "+i + "輪");
					System.out.println("值為: " + current);
					System.out.println("對應的值為:" + cupple);			
				}
			}
		}