Java中如何判断数字是否为回文
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.");
See examples of palindrome detection at the Rosetta Code website.
这是列出的第一个(即 "Non-Recursive" 解决方案)。当然,您必须先将您的号码转换为字符串才能使用此号码:
public static boolean pali(String testMe){
StringBuilder sb = new StringBuilder(testMe);
return testMe.equals(sb.reverse().toString());
}
我对你的 code.Now 做了一些修改,效果很好。
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.");
我无法确定我是否正确地计算了确定用户输入的数字是否为回文的公式(我还需要使用 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.");
See examples of palindrome detection at the Rosetta Code website.
这是列出的第一个(即 "Non-Recursive" 解决方案)。当然,您必须先将您的号码转换为字符串才能使用此号码:
public static boolean pali(String testMe){ StringBuilder sb = new StringBuilder(testMe); return testMe.equals(sb.reverse().toString()); }
我对你的 code.Now 做了一些修改,效果很好。
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.");