2015-02-09 95 views
-1

如果我正确地计算出用户输入的数字是否是回文的公式(我也需要使用一个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."); 
+3

Java不是Python。你当然错过了一些大括号。目前,while循环只执行'rev = num%10;'这可能不是你想要的。 – 2015-02-09 17:45:59

+2

我听起来更容易做一些像'Integer.toString(value).equals(new StringBuilder(Integer.toString(value))。reverse.toString())' – Jack 2015-02-09 17:48:50

+0

ZouZou我会用大括号来尝试它,我猜,我也有从未在Python中编程过。 – Fyree 2015-02-09 17:51:06

回答

0

我做了一些更改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."); 
+0

感谢您的帮助(我不知道为什么这是由某人downvoted)! – Fyree 2015-02-09 18:39:34

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()); 
} 
相关问题