HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Palindrome program

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
palindromeprogramstackoverflow

Problem

Given a beginning and ending point, check how many numbers are palindromic.

My solution is a bit clunky. How could it be more elegant?

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Palindrome {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter starting point: ");
        int start = sc.nextInt();

        System.out.println("Enter finishing point: ");
        int finish = sc.nextInt();

        List numbers = new ArrayList();
        int count = 0;

        for (int i = start; i <= finish; i++) {
            numbers.add(i);
            if(isPalinDrome(i)){
                count++;
            }
        }

        System.out.println("[Start value: " + start + "] [End value: " + finish + "] [Number of PalinDromes: " + count + "]");

    }

    public static boolean isPalinDrome(int n){
        String str = Integer.toString(n);
        String reverse = new StringBuilder(str).reverse().toString();

        return str.equals(reverse);
    }

}

Solution

It's good that you're aware of Stringbuilder's reverse, but let's try to consider the cost of all these mutations.

As it is, before you even begin checking for the palindromic case, to reverse an integer, you're:

-
Changing it to it to a string

-
Passing that string to a new stringbuilder

  • Using stringbuilder's reverse() method, which loops through the


string character by character

  • Changing the result of all this back to a string.



  • Extracting the reverse logic, which would be a good practice, could even mean changing all this string back to an integer.



This method as a general purpose reverse is fine, but our problem scope here deals only with integers, why not also consider implementing a solution dealing strictly with integers?

Reversing an integer can be done by dividing out remainders of 10 until the number is 0. Making sure to multiply the result by 10, before adding additional remainders so it "moves one place."

Let's see this exemplified, take any number, I'll choose 925 for simplicity's sake:

925 % 10 -> 5
925 / 10 -> 92
92 not 0 -> continue

5 * 10 -> 50
92 % 10 -> 2
50 + 2 -> 52
92 / 10 -> 9
9 not 0 -> continue

52 * 10 -> 520
9 % 10 -> 9
520 + 9 -> 529
9 / 10 -> 0
0 -> end


So, turning this to code, to reverse an integer:

public static int reverse(int n) {
  int reversed = 0;   

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

  return reversed;
}


Do note that unlike your current implementation this actually can deal with negative integers without throwing exceptions.

Of course your palindrome method is now simply:

public static boolean isPalindromic(int n) {
    return n == reverse(n);
}


Keep in mind through overloading you can still keep your current method, simply adjusting it purely towards string palindromes. I'd call it a good practice to also extract the reverse logic into its own method however, such would mean your program structure follows the separation of concerns.

Code Snippets

925 % 10 -> 5
925 / 10 -> 92
92 not 0 -> continue

5 * 10 -> 50
92 % 10 -> 2
50 + 2 -> 52
92 / 10 -> 9
9 not 0 -> continue

52 * 10 -> 520
9 % 10 -> 9
520 + 9 -> 529
9 / 10 -> 0
0 -> end
public static int reverse(int n) {
  int reversed = 0;   

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

  return reversed;
}
public static boolean isPalindromic(int n) {
    return n == reverse(n);
}

Context

StackExchange Code Review Q#84943, answer score: 10

Revisions (0)

No revisions yet.