Search code examples
javapalindrome

Java: Palindrome, not getting biggest number


I want to get the largest palindrome number of 3-digit numbers. This is my code:

for (int start = 100; start < 1000; start++) {
        for (int start2 = 100; start2 < 1000; start2++) {
            int temp = start * start2;  
            int biggest = 1;
            String strTemp = temp + "";     

            if (strTemp.equals(new StringBuilder(strTemp).reverse().toString())) {
                if (temp > biggest) {
                    biggest = temp;
                    System.out.println("Original: " + strTemp);
                    System.out.println("Reverse: " + new StringBuilder(strTemp).reverse().toString());
                    System.out.println("Siffra: " + start);
                    System.out.println("Siffra2: " + start2);
                }

            }       
        }

In the end, I get 995 x 583 and not 993 x 913, which is the largest one. Why? I have it so the int biggest always chooses the biggest number.


Solution

  • You need to move int biggest = 1; out of both for loops. If you don't do that at every inner loop you restart the value of biggest.

    int biggest = 1;
    for (int start = 100; start < 1000; start++) {
        for (int start2 = 100; start2 < 1000; start2++) {
            int temp = start * start2;  
    
            String strTemp = temp + "";     
    
            if (strTemp.equals(new StringBuilder(strTemp).reverse().toString())) {
                if (temp > biggest) {
                    biggest = temp;
                    System.out.println("Original: " + strTemp);
                    System.out.println("Reverse: " + new StringBuilder(strTemp).reverse().toString());
                    System.out.println("Siffra: " + start);
                    System.out.println("Siffra2: " + start2);
                }
    
            }       
        }
    

    With java 8 you can rewrite this code as follow:

        // Define what it means palindrome
        IntPredicate isPalindrome = n -> new StringBuffer(String.valueOf(n)).reverse().toString().equals(String.valueOf(n));
    
    
        OptionalInt max = 
                 // Define a stream from 100 to 1000
                 IntStream.range(100, 1000)   
                 // Map the original stream to a new stream 
                 // Basically for each x of the first stream
                 // creates a new stream 100-1000 and map each element
                 // x of the first stream and y of the second stream
                 // to x * y
                .flatMap(x -> IntStream.range(100, 1000).map(y -> x * y))
                 // Take only palyndrome of x * y
                .filter(isPalindrome)
                // take the max
                .max();
    

    A functional approach is more readable in most cases where you have to loop over n elements and is easier to filter and extract elements without doing errors.