Tsundoku
Tsundoku

Reputation: 9408

Can't find the error in my code for number 4 of project euler

I am trying to solve the following problem:

Find the largest palindrome made from the product of two 3-digit numbers.

I have the following Java code:

public static void main(String[] args) {
        int a = 999, b = 999;
        for(int i = 100; i <= a; i++) {
            for(int j = 100; j <= b; j++) {
                checkPalindrome(i*j, i, j);
            }
        }
    }

    public static void checkPalindrome(int n, int a, int b) {
        String s = "" + n;
        boolean palindrome = false;
        int j = s.length()-1;

        for(int i = 0; i < s.length(); i++){
            if(s.charAt(i) != s.charAt(j))
                break;
            j -= i;
        }

        if(palindrome)
            System.out.println(n + ", " + a + ", " + b);
    }

I'm still lacking the change of the "palindrome" variable but at the moment if I run it I get a String index out of range on line 28 which is the j -= i I just don't understand why this is happening I mean, I get that the difference is resulting in a number lower than 0 but I can't figure out WHY it happens. Could someone please explain me?

Upvotes: 0

Views: 125

Answers (4)

Nir Alfasi
Nir Alfasi

Reputation: 53535

change your code to:

public static void checkPalindrome(int n, int a, int b) {
        String s = "" + n;
        boolean palindrome = true;
        int j = s.length()-1;

        for(int i = 0; i < s.length(); i++){
            if(s.charAt(i) != s.charAt(j))
                palindrome = false;
        }

        if(palindrome)
            System.out.println(n + ", " + a + ", " + b);
    }

Upvotes: 1

Ravindra Gullapalli
Ravindra Gullapalli

Reputation: 9158

Your method can be improved like this. The condition in for loop i<=j reduced number of iterations too.

public static void checkPalindrome(int n, int a, int b) {
    String s = "" + n;
    boolean palindrome = false;
    int j = s.length()-1;

    for(int i = 0; i <= j; i++){
        if(s.charAt(i) != s.charAt(j))
            break;
        j --;
    }

    if(palindrome)
        System.out.println(n + ", " + a + ", " + b);
}

Hope this helps.

Upvotes: 1

James
James

Reputation: 8586

You're incrementing i - you want to decrement j - you DON'T want to do j -= i.

Otherwise for a string of length 5, you'd get:

i = 0, j = 4

i = 1, j = 4

i = 2 , j = 3

i = 3 , j = 1

i = 4, j = -2

Though if it's giving an index out of range message, you're running a different version of the code - j -= i can't possibly generate that.

Upvotes: 0

Gregor Thomas
Gregor Thomas

Reputation: 145785

I think you want j-- not j -= i. Especially since i starts at 0.

Upvotes: 1

Related Questions