Largest Palindrome Product – Leetcode

Problem

Find the largest palindrome made from the product of two n-digit numbers. Since the result could be very large, you should return the largest palindrome mod 1337.

Example:

Input: 3  ,  Output: 987

Explanation:

99 x 91 = 9009, 9009 % 1337 = 987

Note:  The range of n is [1,8].

Solution

package com.programtalk.learn.interview.questions;

public class LargestPalindromeProduct {
	public static void main(String[] args) {
		for (int i = 2; i < 9; i++) {
			System.out.println("input: " + i);
			int largestPalindrome = new LargestPalindromeProduct().largestPalindrome(i);
			System.out.println("plaindrome % 1337 is : " + largestPalindrome + "\n\n");

		}
	}

	public int largestPalindrome(int n) {
		if (n == 1) {
			return 9;
		}
		// if n = 3 then max = 999
		int upperBound = (int) Math.pow(10, n) - 1;
		int lowerBound = upperBound / 10;
		for (int v = upperBound - 1; v > lowerBound; v--) {
			// creates maximum assumed palindrom
			// e.g. if n = 3 first time the maximum assumed palindrom will be
			// 998 899
			long palindrome = Long.valueOf(v + new StringBuilder().append(v).reverse().toString());
			for (long x = upperBound; x * x >= palindrome; x--) {
				if (palindrome % x == 0) {
					System.out.println("numbers multiplied : " + x + " * " + palindrome / x);
					System.out.println("palindrome :" + palindrome);
					return (int) (palindrome % 1337);
				}
			}
		}
		return 0;
	}
}

And if don’t like to use StringBuilder.reverse() then you can use the below function to reverse the number

	public int reverseInt(int input) {
		long reversedNum = 0;

		long input_long = input;

		while (input_long != 0) {
			reversedNum = reversedNum * 10 + input_long % 10;
			input_long = input_long / 10;
		}

		if (reversedNum > Integer.MAX_VALUE || reversedNum < Integer.MIN_VALUE) {
			throw new IllegalArgumentException();
		}
		return (int) reversedNum;
	}

Output


input: 2
numbers multiplied : 99 * 91
palindrome :9009
plaindrome % 1337 is : 987


input: 3
numbers multiplied : 993 * 913
palindrome :906609
plaindrome % 1337 is : 123


input: 4
numbers multiplied : 9999 * 9901
palindrome :99000099
plaindrome % 1337 is : 597


input: 5
numbers multiplied : 99979 * 99681
palindrome :9966006699
plaindrome % 1337 is : 677


input: 6
numbers multiplied : 999999 * 999001
palindrome :999000000999
plaindrome % 1337 is : 1218


input: 7
numbers multiplied : 9998017 * 9997647
palindrome :99956644665999
plaindrome % 1337 is : 877


input: 8
numbers multiplied : 99999999 * 99990001
palindrome :9999000000009999
plaindrome % 1337 is : 475

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.