I'm writing a code in Java where input is a user generated integer string and I have to reverse the integer and check for boolean true or not. I'm stuck at the math portion because I can't exactly figure out the mathematical process of trying to reverse an integer.

// Scanner
        Scanner input = new Scanner(System.in);
        System.out.print("Please enter an integer: ");
        int number = input.nextInt();
        
        // Initialize variables
        int d = number;
        int i = reverse(d);
        int j = isPalindrome(d);
    }
        // Reverse Method
        public static int reverse(int d){
             for (int i = 0; i <= d; i++){
                 int r = d % 10;
                 d = d / 10;
             }
                 
        }

I don't know if I should use a while loop or a for loop. But that's where my code is right now.

Recommended Answers

All 2 Replies

You can convert the int to a String. It will be easier then. Check the String class API.

int i = 123;
String s = String.valueOf(i); // now s="123"

// then use the String methods
char [] ch = s.toCharArray();

You can loop the array backwards and generate a new String from that. Then you can compare the original String with the new String to see if it is a palindrome.

If this approach is not allowed by your teacher and you need to use only mathematics and numbers then let us know

To help you see what is happening as you do the math, print out the values as they are generated.
Think of a decimal number in these terms where di is a decimal digit value 0-9:
1000*d1 + 100*d2 + 10*d3 + d4
when you reverse this number the d1 to d4 are reversed to d4 thru d1

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.