# Concise C++ solution

• Inspired by @chiranjeeb2

``````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--) {
long cand = buildPalindrome(i);
for (long j = upper; j*j >= cand; j--) {
if (cand % j == 0 && cand / j <= upper) {
return cand % 1337;
}
}
}
return -1;
}

long buildPalindrome(int n) {
string s = to_string(n);
reverse(s.begin(), s.end());
return stol(to_string(n) + s);
}
};
``````

• @Hcisly Thanks for the solution. One question about buildPalindrome() method. when you pass 99999999, it should return 9999999999999999. How does it return this large number as a long?

• @amin__ Good question. it depends on OS arch. Strictly the code only works on the OS which MAX_LONG is 2^63 - 1 (9223372036854775807). All current 64-bit architecture systems have such limits. LC is running on such a system and that is why the code works. If you migrate the code to an old 32-bit system, it may break.
https://en.wikipedia.org/wiki/64-bit_computing#64-bit_data_models

• @Hcisly Oh. Thanks for the reply :)

• Hi, I think `if (cand % j == 0 && cand / j <= upper)` can be simplifies as `if(cand%j == 0)`. Do you think so?

• @Hao-Cai This is to ensure the case where cand / j > upper (cand / j > n-digit). This does not happen in range [1,8] but may happen for larger n.

• @Hcisly you construct the palindrome by reverse the string, like abba style, what if the answer is abcba style?

Do we have a way to prove that abcba is not possible to be the answer?

• @Vincent-Cai I don't think so. For example cand=9999, upper = 99

• @beetlecamera I didn't try to prove it. But intuitively, the largest palindrome product of two n digit number will be 2n digits when n > 1.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.