Java程式檢查迴文
迴文一詞來源於希臘語“palin dromo”,意思是“再次返回”。一個數字、字串或短語,當反轉時保持不變,即反向讀取與正向讀取相同,則稱為迴文。例如,數字迴文包括525、2002和12121等數字。而單詞迴文則有“ABA”、“BABAB”和“RADAR”等。要檢查Java中的迴文,我們可以使用while迴圈和if-else塊來確定給定的數字或字串及其反轉是否相同。
Java程式檢查迴文
在本節中,我們將編寫不同的Java程式來檢查給定的輸入是否為迴文。在此之前,讓我們藉助示例來討論問題陳述。
示例
輸入1
121
輸出
121 is a Palindrome
輸入2
34431
輸出
34431 is not a Palindrome
輸入3
"ABABA"
輸出
ABABA is a Palindrome
現在,讓我們進入Java程式來檢查迴文。
示例1
在本例中,我們將從使用者那裡獲取一個數字作為輸入,並檢查該數字是否為迴文。我們還將藉助while迴圈和if-else條件塊。
import java.util.*; public class Example1 { public static void main(String[] args) { // creating an instance of Scanner class Scanner sc=new Scanner(System.in); System.out.println("Enter a number to check palindrome: "); // to take input from user int num = sc.nextInt(); // copying the original input int copy = num; // variable to store the result int revVal = 0; // loop to check palindrome while(copy != 0) { int rem = copy % 10; // extracting remainder copy /= 10; // dividing and storing the number revVal = revVal * 10 + rem; // reversing } // checking whether the reverse and original number is same or not if(num == revVal) { System.out.println(num + " is a Palindrome number"); } else { System.out.println(num + " is not a Palindrome number"); } } }
輸出1
Enter a number to check palindrome: 323 323 is a Palindrome number
輸出2
Enter a number to check palindrome: 258 258 is not a Palindrome number
示例2
以下示例說明了如何檢查字串是否為迴文。我們將使用StringBuffer類的名為reverse()的內建方法來反轉給定的字串。然後,我們將此反轉後的字串傳遞給equals()方法,以檢查原始字串和反轉後的字串是否相同。如果兩者相同,則字串為迴文,否則不是。
public class Example2 { public static void main (String[] args) { String str = "ABABA"; System.out.println("The original String is: " + str); // reversing the original string String strRev = new StringBuffer(str).reverse().toString(); // checking whether the reverse is equal to the original string if (str.equals(strRev)) { System.out.println(str + " is a Palindrome!"); } else { System.out.println(str + " is not a Palindrome!"); } } }
輸出
The original String is: ABABA ABABA is a Palindrome!
示例3
這是另一個Java程式,用於檢查給定的數字是否為迴文。
public class Example3 { public static void main(String[] args) { int num = 52525; System.out.println("The original number is: " + num); // copying the original input int copy = num; // variable to store the result int revVal = 0; // loop to check palindrome while(copy != 0) { int rem = copy % 10; // extracting remainder copy /= 10; // dividing and storing the number revVal = revVal * 10 + rem; // reversing } // checking whether the reverse and original number is same or not if(num == revVal) { System.out.println(num + " is a Palindrome number"); } else { System.out.println(num + " is not a Palindrome number"); } } }
輸出
The original number is: 52525 52525 is a Palindrome number
結論
在本文中,我們學習了Java中的迴文。此外,我們還討論了不同的Java程式,這些程式說明了如何檢查給定的輸入是否為迴文。實現此目的最直接的方法是使用StringBuffer類的名為reverse()的內建方法。
廣告