From b08fa710dc2e1fcd18dc99828aa5120830fc7b31 Mon Sep 17 00:00:00 2001 From: Ved Prakash Bhaskar <56016547+iamvpbhaskar@users.noreply.github.com> Date: Tue, 26 Oct 2021 21:32:38 +0530 Subject: [PATCH] Creted largest-palindrome-product.cpp --- CPP/largest-palindrome-product.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 CPP/largest-palindrome-product.cpp diff --git a/CPP/largest-palindrome-product.cpp b/CPP/largest-palindrome-product.cpp new file mode 100644 index 0000000..f6513ef --- /dev/null +++ b/CPP/largest-palindrome-product.cpp @@ -0,0 +1,29 @@ +// Time: O(10^(2n)) +// Space: O(n) + +class Solution { +public: + int largestPalindrome(int n) { + if (n == 1) { + return 9; + } + int upper = pow(10, n) - 1; + int lower = pow(10, n - 1); + for (int i = upper; i >= lower; --i) { + auto candidate = buildPalindrome(i); + for (long long j = upper; j * j >= candidate; --j) { + if (candidate % j == 0) { + return candidate % 1337; + } + } + } + return -1; + } + +private: + long long buildPalindrome(int n) { + string s = to_string(n); + reverse(s.begin(), s.end()); + return stoll(to_string(n) + s); + } +};