Largest palindrome made from the product of two 3-digit numbers 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 &lt;=999;i++) {
            for(int j = i;j &lt;=999;j++) {
                int value1 = i * j;
                StringBuilder sb1 = new StringBuilder(""+value1);
                String sb2 = ""+value1;
                sb1.reverse();
                if(sb2.equals(sb1.toString()) &amp;&amp; value&lt;value1) {
                    value = value1;
                }                    
            }
        }

        System.out.println(value);
    }
}


Are there any optimizations/simplifications that we can do in this program?
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()) &amp;&amp; ....) {



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) &amp;&amp; ....) {


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.