Java Palindrome和逆序整数

时间:2014-03-17 04:57:43

标签: java reverse palindrome

我的代码的逆序部分出了问题。我将值存储在hund,tens,ones等中。如何将数据传递回main方法以便以相反的顺序显示这些数字?

import java.util.Scanner;

public class PP53v2 {

    public static void main(String[] args) {

    int leftOver = 0;
    int number = 0;
    int num1;
    Scanner input = new Scanner(System.in);
    System.out.println("Hit #1 to reverse a number. Hit #2 to return if its a palindrome.");
    int selection = input.nextInt();

        switch(selection) {
        //problem 1
        case 1:
        System.out.println("Enter a number to be displayed in reverse order.");
        System.out.println("For accuracy, this must be a five digit number.");
        number = input.nextInt();
        num1 = reverse(number);
        System.out.print(num1);
        break;

        //problem 2
        case 2:
        System.out.println("Enter an integer to see if it's a palindrome.");
        System.out.println("For accuracy, this must be a five digit number. (I.E. 12321 is a palindrome)");
        number = input.nextInt();
        if (isPalindrome(number)) {
            System.out.println("The number is a palindrome." + number);
        } else
            System.out.println("The number isn't a palindrome." + number);

        break;

        }//switch end

    }//main end

    public static int reverse(int number) {

    String leftOver = 0;
    int remaining =0;
    int tenThou = 0, thou = 0, tens = 0, ones = 0; //no need for hundreds

            while (number > 0) {

                tenThou = number / 10000;
                thou = number % 10000 / 1000;
                tens = number % 100 /10;
                ones =  number % 10;

                //remaining = number % 10;
                //number = number / 10;
                //leftOver = leftOver + remaining;
            }//end while
            return leftOver;
    }// reverse method end

    public static boolean isPalindrome(int number) {

    int tenThou = 0, thou = 0, tens = 0, ones = 0; //no need for hundreds

    tenThou = number / 10000;
    thou = number % 10000 / 1000;
    tens = number % 100 /10;
    ones =  number % 10;

    if (tenThou == ones && thou == tens)
        return true;
        else
        return false;

    }//method end

}//class end

1 个答案:

答案 0 :(得分:0)

使用此逻辑

while( n != 0 )
      {
          reverse = reverse * 10;
          reverse = reverse + n%10;
          n = n/10;
      }

n是整数(您的输入)。