2014年12月26日 星期五

java程式設計題目---數字處理【迴文判斷(使用method)】

Write the methods with the following headers:
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; 
 }
}

沒有留言:

張貼留言

Go(Golang)程式語言 設定GCC

下載MSYS2:  https://www.msys2.org/ 安裝 程式開始執行後輸入: pacman -Syu y y 在安裝目錄底下找到msys2.exe,雙擊執行 輸入指令: pacman -Su pacman -S --needed base-devel mingw-...