largest palindrome product in java -
i have written code fourth question of euler project.
the question is: palindromic number reads same both ways. largest palindrome made product of 2 2-digit numbers 9009 = 91 × 99.
find largest palindrome made product of 2 3-digit numbers.
here code:
public class largestpalindromeproduct { private static int product;//integer palindrome number private static string palindrome;//string palindrome private static int largestpalindrome(){ for(int = 100; i<=999; i++){ for(int k = 100; k<=999; k++){ product = i*k; palindrome = integer.tostring(product); for(int j = 0; j<= palindrome.length()-1; j++){ if(palindrome.charat(j) == palindrome.length() - 1 - j){ return product; } } } } return product; } public static void main(string[] args) { int largestpalindrome = largestpalindrome(); system.out.println(largestpalindrome); }
}
this code gives 998001 output. can me find problem is?
close, pattern work, must try combinations , return largest one. also, don't short circuit method on mis-match, break out of loop.
try couple changes similar i've added...
public class largestpalindromeproduct { private static int largestpalindrome() { int max = 0; for(int = 100; i<=999; i++) { for(int k = 100; k<=999; k++) { int product = i*k; if (product <= max) { continue; } string palindrome = integer.tostring(product); boolean = true; for(int j = 0; j<= palindrome.length()-1; j++) { if(palindrome.charat(j) != palindrome.charat(palindrome.length() - 1 - j)) { = false; break; } } if (good) max = product; } } } return max; } public static void main(string[] args) { int largestpalindrome = largestpalindrome(); system.out.println(largestpalindrome); }
Comments
Post a Comment