[英]How to tell if the number is a palindrome or not in Java
我無法弄清楚是否正確地執行了公式來弄清楚用戶輸入的數字是否是回文(也需要使用while循環)。 我算算對嗎? 當我嘗試輸入數據時,它只是坐在那里,什么也不做。 這是代碼:
System.out.print("Enter the number you would like to be checked if it is a palindrome:");
int num = input.nextInt();
int rev = num % 10;
int count = 1;
int i = 0;
int originalNum = num;
while(count < 2)
rev = num % 10;
num = num / 10;
i = i*10 + rev;
count = count + 1;
if(originalNum == i)
System.out.println("The number you input is a palindrome.");
else
System.out.println("The number you input is not a palindrome.");
這是列出的第一個(即“非遞歸”解決方案)。 當然,您必須首先將數字轉換為字符串,才能使用此數字:
public static boolean pali(String testMe){ StringBuilder sb = new StringBuilder(testMe); return testMe.equals(sb.reverse().toString()); }
我對您的代碼做了一些更改。現在,它可以工作了。
int num = input.nextInt();
int rev=0;
int i = 0;
int originalNum = num;
while(num!=0){
rev = num % 10;
i = i*10 + rev;
num = num / 10;
}
if(originalNum == i)
System.out.println("The number you input is a palindrome.");
else
System.out.println("The number you input is not a palindrome.");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.