0

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.

3
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by NormR1
0

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

0

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.