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

Largest palindrome made from the product of two 3-digit numbers

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

Problem

I am working on an interview question in which I need to find the largest palindrome made from the product of two 3-digit numbers. Here is the question.

public class PalindromeThreeDigits {

    public static void main(String[] args) {
        int value = 0;
        for(int i = 100;i <=999;i++) {
            for(int j = i;j <=999;j++) {
                int value1 = i * j;
                StringBuilder sb1 = new StringBuilder(""+value1);
                String sb2 = ""+value1;
                sb1.reverse();
                if(sb2.equals(sb1.toString()) && value<value1) {
                    value = value1;
                }                    
            }
        }

        System.out.println(value);
    }
}


Are there any optimizations/simplifications that we can do in this program?

Solution

When checking to see if a number is a palindrome, you effectively do:

StringBuilder sb1 = new StringBuilder(""+value1);
String sb2 = ""+value1;
sb1.reverse();
if(sb2.equals(sb1.toString()) && ....) {


That should be extracted to a function:

private static boolean isPalindromeSB(final int value1) {
    StringBuilder sb1 = new StringBuilder(""+value1);
    String sb2 = ""+value1;
    sb1.reverse();
    return sb1.equals(sb2);
}


so that you can use it as follows:

if (isPalindromeSB(value1) && ....) {


That neatens up your code, and does what is called "Functional Extraction".

Additionally, if you look at that function it does a lot of work... it does 2 string concatenations, creating three Strings, a StringBuilder, and a bunch more.

It would be more efficient to keep everything as numbers, and have a function like:

private static boolean isPalindrome(final int product) {
    int p = product;
    int reverse = 0;
    while (p != 0) {
        reverse *= 10;
        reverse += p % 10;
        p /= 10;
    }
    return reverse == product;
}


Note that this creates only two int values.... and it loops once per digit.

I tested it, and it is about 4 times faster than the String version.

Code Snippets

StringBuilder sb1 = new StringBuilder(""+value1);
String sb2 = ""+value1;
sb1.reverse();
if(sb2.equals(sb1.toString()) && ....) {
private static boolean isPalindromeSB(final int value1) {
    StringBuilder sb1 = new StringBuilder(""+value1);
    String sb2 = ""+value1;
    sb1.reverse();
    return sb1.equals(sb2);
}
if (isPalindromeSB(value1) && ....) {
private static boolean isPalindrome(final int product) {
    int p = product;
    int reverse = 0;
    while (p != 0) {
        reverse *= 10;
        reverse += p % 10;
        p /= 10;
    }
    return reverse == product;
}

Context

StackExchange Code Review Q#88084, answer score: 4

Revisions (0)

No revisions yet.