Hackerrank – Problem description
The problem description – Hackerrank.
Solution
We need to find out if the product of two 3-figured number is a palindrome and it is smaller than exercise upper constraint.
My solution starts with initializing two numbers as 999
. I continually decremented second number by 1
, until it is equal to 100
. I calculated the product for each pair. If the product is palindrome and compare it with actual maximum of products.
Repeat the steps until both numbers are equal to 100
. The result is actual maximum palindrome number
9992
does not exceed exercise time limit.
I created solution in:
All solutions are also available on my GitHub profile.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
import java.util.Scanner; public class LargestPalindromeProduct { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int tests = Integer.parseInt(scanner.nextLine()); for (int i = 0; i < tests; i++) { int number = Integer.parseInt(scanner.nextLine()); System.out.println(palindromeNumber(number)); } scanner.close(); } private static int palindromeNumber(int number) { // int root = (int) Math.sqrt(number); int max = 0; for (int j = 999; j >= 100; j--) { for (int k = 999; k >= 100; k--) { int product = j * k; if(product < number && isPalindrome(String.valueOf(product))) { if(product > max) { max = product; } } } } return max; } private static boolean isPalindrome(String text) { for (int i = 0; i < text.length() / 2; i++) { if(text.charAt(i) != text.charAt(text.length() - 1 - i)) { return false; } } return true; } } |