public static int reverse(int number)
public static Boolean isPalindrome(int number)
Use the reverse method to implement isPalindrome. A number is a palindrome if its reversal is the same as itself. Write a test program that prompts the user to enter an integer and reports whether the integer is a palindrome.
import java.util.Scanner; public class C1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("請輸入整數:"); int number = input.nextInt(); int startnumber = number; //要先將原本輸入的值存近來,不然之後會被覆蓋掉。 需特別注意!!! //呼叫 reverse 和 isPalindrom System.out.println(reverse(number)); number = startnumber;//呼叫使用者最原始輸入的那個值 System.out.println(isPalindrom(number)); } public static int reverse(int number) { int[] array = new int[10]; int i = 0; int z = number; int count = 1; int t = 1; int result = 0; while(number > 0) { int a = number % 10; array[i] = a; z = number / 10 ; number = z; i++ ; count = count + 1; } for(int a = count - 2 ; a >= 0 ; a--) { int c = array[a] * t ; result = result + c; t = t * 10; } return result; } // public static boolean isPalindrom(int number) { int inputnumber = number ; //要先將原本輸入的值存近來,不然之後會被覆蓋掉。 需特別注意!!! int[] array = new int[10]; int i = 0; int z = number; int count = 1; int t = 1; int result = 0; boolean bool = new Boolean(true) ; while(number > 0) { int a = number % 10; array[i] = a; z = number / 10 ; number = z; i++ ; count = count + 1; } for(int a = count - 2 ; a >= 0 ; a--) { int c = array[a] * t ; result = result + c; t = t * 10; } if( inputnumber == result ) { bool = true ; } else if(inputnumber != result) { bool = false ; } return bool; } }
沒有留言:
張貼留言