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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…