Why is parseInt not working in my code for project Euler #4 in java?

Vasila_M

I tried solving Project Euler #4 by converting my number to a string, reversing it, and converting it back into a number. The problem is commented out in my code.

package euler.proj;

public class Main {

    public static void main(String[] args) {
        //A palindromic number reads the same both ways.
        // The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
        //Find the largest palindrome made from the product of two 3-digit numbers.
        int palindrome = 0;
        String reverse = "";
        for(int i = 100*100; i<= 999*999; i++){
            String pal = Integer.toString(i);
            for(int j = pal.length()-1; j >= 0; j--)
                reverse = reverse + pal.charAt(j);
            int k = Integer.parseInt(reverse);
            if (k == i)
                palindrome = k;
        }
        System.out.println("The largest palindromic product of two 3-digit numbers is " + palindrome);
    }
}

The program doesn't compile and IntelliJ gives these errors:

Exception in thread "main" java.lang.NumberFormatException: For input string: "000011000120001"

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:461)
at java.lang.Integer.valueOf(Integer.java:554)
at euler.proj.Main.main(Main.java from InputFileObject:15)
Pieter12345

The number 000011000120001 (or 11.000.120.001 in different notation) does not fit in a 4 byte Integer (ranging from roughly -2.147.000.000 to 2.147.000.000). You can use Long.parseLong(number) for your application.

Edit: Additionally, you should move String reverse = ""; within your for-loop, as you are currently appending all numbers that you are testing to it after each other, resulting in a gigantic number.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related