LargestPalindromeProduct.java 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /* A palindromic number reads the same both ways. The largest palindrome made
  2. from the product of two 2-digit numbers is 9009 = 91 × 99.
  3. Find the largest palindrome made from the product of two 3-digit numbers.
  4. */
  5. class LargestPalindromeProduct {
  6. private long largestPalindrome;
  7. public LargestPalindromeProduct() {
  8. this.largestPalindrome = this.calculateLargestPalindrome();
  9. }
  10. public long getLargestPalindrome() {
  11. return this.largestPalindrome;
  12. }
  13. private boolean checkPalindrome(long num) {
  14. // It's easier to compare characters if they're strings
  15. String numString = Long.toString(num);
  16. StringBuilder reverseStringBuilder = new StringBuilder(numString).reverse();
  17. String reverseString = reverseStringBuilder.toString();
  18. if ( numString.equals(reverseString) )
  19. return true;
  20. return false;
  21. }
  22. private long calculateLargestPalindrome() {
  23. long largestPalindrome = 0;
  24. for (long i = 100; i <= 999; i++) {
  25. for (long j = 100; j <= 999; j++) {
  26. long product = i * j;
  27. if ( checkPalindrome(product) ) {
  28. if (product > largestPalindrome)
  29. largestPalindrome = product;
  30. }
  31. else
  32. continue;
  33. }
  34. }
  35. return largestPalindrome;
  36. }
  37. }