我无法弄清楚我是否正确地使用公式来确定用户输入的数字是否是回文(我还需要使用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.");
答案 0 :(得分:1)
See examples of palindrome detection at the Rosetta Code website
这是列出的第一个(即“非递归”解决方案)。当然,您必须首先将您的号码转换为String,以使用此号码:
public static boolean pali(String testMe){ StringBuilder sb = new StringBuilder(testMe); return testMe.equals(sb.reverse().toString()); }
答案 1 :(得分:1)
我对你的代码进行了一些更改。现在,它有效。
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.");