Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

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

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)
question from:https://stackoverflow.com/questions/65848231/why-is-parseint-not-working-in-my-code-for-project-euler-4-in-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...