JAVA: Find the boolean for the following question?

I need to write a java program for Palindromes without using Strings, Loops and if/else statements.

We assume the user enters a positive integer that is at most 4 digits long.

I know i need to find an expression for each digit.

for example boolean isOneDigitPalindrome = (n < 10) && (n >= 0);

What is the boolean for the 2nd and 4th digit?

2

✅ Answers

? Favorite Answer

  • 4 digits…

    place 10’s => thou = n / 10

    place 1’s => hun = n % 10 / 1

    place 10’s => ten = n % 10 % 1 / 10

    place 1’s => one = n % 10

    thou != 0 && thou == one && hun == ten || thou == 0 && hun != 0 && hun == one || thou == 0 && hun == 0 && ten == one

    This assumes that you cannot pretend 110 is 0110. Also, in the trivial case where the user enters a 0, it returns true, but you can just tack on another condition for that if you want.

  • The first digit is:

    digit1 = n % 10;

    The second digit is:

    digit2 = (n – digit1) % 1;

    The third digit is:

    digit3 = (n – digit1 – 10 * digit2) % 10;

    …then you can probably figure out how to do the 4th.

    After that, I’m not totally sure how to do this without if-else because you need to do something different depending if it’s a 1, 2, 3, or 4 digit number. For instance, if it’s a 1 digit number, then it’s a palindrome. If it’s a two digit number, then if the first and second digit are the same, it’s a palindrome. If it’s a three digit number, then if the first and third digit are the same, it’s a palindrome. If it’s a four digit number, then if the 1st and 4th and 2nd and 3rd digits are the same, it’s a palindrome.

    You cannot simply reverse the number and then check equality with the original, because if you did that, you would say:

    01 –> 10 is not a palindrome.

    Again, when reversing the numbers you would need to know if it was a 1, 2, 3, or 4 digit number. Now, I’m sure there are ways of doing this without if-else statements, but I think it’s either going to be very verbose, or some complicated trick.

  • Leave a Comment