【问题标题】:How to tell if the number is a palindrome or not in Java如何在Java中判断数字是否是回文
【发布时间】:2015-02-09 17:44:39
【问题描述】:

我无法确定我是否正确地执行了确定用户输入的数字是否为回文的公式(我还需要使用 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.");

【问题讨论】:

  • Java 不是 Python。你肯定错过了几个大括号。目前,while 循环只执行rev = num % 10;,这可能不是您想要的。
  • 我听起来更容易做类似Integer.toString(value).equals(new StringBuilder(Integer.toString(value)).reverse.toString())的事情
  • ZouZou 我想我会用大括号试试,而且我以前从未用 Python 编程过。
  • 我想知道的是我的公式是否正确(由于某种原因,当我输入数字时没有打印出来)。
  • 是时候学习如何调试了。

标签: java while-loop int java.util.scanner palindrome


【解决方案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.");

【讨论】:

    【解决方案2】:

    See examples of palindrome detection at the Rosetta Code website.

    这是列出的第一个(即“非递归”解决方案)。当然,您必须先将您的号码转换为字符串,才能使用这个:

    public static boolean pali(String testMe){
      StringBuilder sb = new StringBuilder(testMe);
      return testMe.equals(sb.reverse().toString());
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 2015-11-15
      • 1970-01-01
      • 2010-12-11
      • 1970-01-01
      • 2015-05-03
      • 2010-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多