java Java程序反转一个数字并确定它是否是回文

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13226032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:57:27  来源:igfitidea点击:

Java program Reversing a number and determining if it is a Palindrome

javamethodsreturnreversepalindrome

提问by BraxtonLanc

as homework I am to write two methods; one that is a reversal method using public static int(int number) while the other is a Palindrome method using public static boolean isPalindrome(int number). I've been working on this for a couple hours and am honestly stumped. I'm not asking for my homework to be done for me, just help in understanding where to go from here. Thanks. My current code is as follows;

作为作业我要写两个方法;一个是使用 public static int(int number) 的反转方法,而另一个是使用 public static boolean isPalindrome(int number) 的回文方法。我已经为此工作了几个小时,老实说我很难过。我不是要求为我完成作业,只是帮助了解从这里开始的方向。谢谢。我目前的代码如下;

public class Exercise
{
    public static void main(String[] args)
    {

        System.out.println("Please enter an integer. ");
        Scanner input = new Scanner(System.in);
        int number = input.nextInt();
        boolean Final = isPalindrome(number);
        System.out.println(Final);

    }

    public static int reverse(int number)
    { // missing return?
        int y;
        int n;
        for (n = 0; n <= number; n++)
        { // parameters
            y = number % 10; // remainder
            number = number / 10; // gets rid of last digit
            n = n * 10 + y; // sets reverse values

            return n; // returns reversed number
        }
    }

    public static boolean isPalindrome(int number)
    {
        int n = reverse(number); // call reverse method
        boolean result; // declare result
        if (n = number)
        { // incompatible types?
            result = true;
            System.out.println("The number " + number + " is a " + "Palindrome" + ".");
        }
        else if (n != number)
        {
            result = false;
            System.out.println("The number " + number + " is a Palindrome" + ".");
        }
        return result; // not initialized?
    }
}

回答by durron597

Your return n;is inside the forloop. Just move the curly brace to above it.

return n;for循环内。只需将花括号移到其上方即可。

Also, change the forloop to while (number > 0) {

另外,将for循环更改为while (number > 0) {

And change (n = number)to (n == number)

并更改(n = number)(n == number)

Also, delete the second ifcondition in isPalindrome, you don't need it. Just put else. That will make the compiler tell you that return result;is unreachable... just delete it.

另外,删除 中的第二个if条件isPalindrome,您不需要它。就放else。这将使编译器告诉您return result;无法访问...只需将其删除即可。

回答by kjana83

Problem in reverse logic.

逆逻辑问题。

try this

试试这个

 public static int reverse(int number)
        {  
            int result = 0;
            int remainder;
            while (number > 0)
            {
                remainder = number % 10;
                number = number / 10;
                result = result * 10 + remainder;
            }

            return result;
        }

回答by Jiman

It's easier to work with strings for palindromes IMO.

使用回文字符串更容易 IMO。

Souce post: How do you determine if a String is a palindrome?

来源帖子: 你如何确定一个字符串是否是回文?

int someNumber = 12321;
String palindrome = someNumber+"";
boolean isPalindrome = palindrome.equals(new StringBuilder(palindrome).reverse().toString());

With your code, it would be:

使用您的代码,它将是:

public static void main(String[] args)
{

    System.out.println("Please enter an integer. ");
    Scanner input = new Scanner(System.in);
    int number = input.nextInt();
    String palindrome = number+"";
    boolean result = palindrome.equals(new StringBuilder(palindrome).reverse().toString());
    System.out.println(result);

}

回答by Yatin Dabhat

/* Palindrome program using methods and Interface */

/* 回文程序使用方法和接口 */

 import java.util.Scanner;

 interface Test    //  All methods inside interface are treated "Public"
    {                 //  and abstract in nature by default   
String getInput();
boolean IsPalindrome(String s);
void displayInput();
         }

  abstract class Sub_Test  implements Test
       {
   public String getInput()
   {
       Scanner scan = new Scanner(System.in);
       System.out.println("Enter a String ");
       String str = scan.nextLine();
       return str;
   }
   public boolean IsPalindrome(String s)
       { 
       int limit = s.length() - 1;
       char st1 [] = s.toCharArray();
   Inner:for( int i = 0,j = limit; i < j ; i++,j--)
       {
           if(st1[i] == st1[j])
               return true;
           else 
               break Inner;
       }
              return false;
   }
          public void displayInput()
            {
      String input = getInput();
      boolean word = IsPalindrome(input);
      if(word)
        System.out.println("Given String "+input+" is palindrome ");
      else
        System.out.println("Given String "+input+" is NOT palindrome ");
                }   // End of displayInput() method

             }  // End of Sub_test abstract class

    public class String_Session1 extends Sub_Test {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String_Session1 object = new String_Session1();
    object.displayInput();
}
          }  // End of String-Session1 Main class

/* The output is as below */

/* 输出如下 */

   Enter a String 
   Race CAR

   Given String Race CAR is palindrome

回答by Sree

If you are writing for Number palindrome. here's the tip:

如果您正在为数字回文写作。这是提示:

boolean method

布尔方法

public static boolean ispalindrome(int number)
    {
        int num=reverse(number);
        boolean res;
        if (num == number){
            res=true;
        System.out.println("The Entered number "+number+ " is a palindrome");}
        else {
            res=false;
            System.out.println("The Entered number "+number+" is not a palindrome");}
        return res;
    }


in your main method ,

在你的主要方法中,

boolean Res=ispallindrome(number);  

can be used to check the condition.

可用于检查条件。

回答by huseyin

Simply get the digit count of the number via Math functions and then iterate by using '/' and '%' operations as follows. After x = (x % divider) / 10, we should divide divider by 100 since we made 2 zero operations.

只需通过数学函数获取数字的位数,然后使用 '/' 和 '%' 操作进行迭代,如下所示。在 x = (x % Divider) / 10 之后,我们应该将除数除以 100,因为我们进行了 2 次零操作。

public static boolean isPalindrome(int x) {
        if (x < 0) return false;
        if (x < 10) return true;

        int numDigits = (int)(Math.log10(x)+1);
        int divider = (int) (Math.pow(10, numDigits - 1));
        for (int i = 0; i < numDigits / 2; i++) {
            if (x / divider != x % 10)
                return false;
            x = (x % divider) / 10;
            divider /= 100;
        }
        return true;
    }