Concise C++ solution


  • 3
    H

    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);
        }
    };
    

  • 0
    A

    @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?


  • 0
    H

    @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


  • 0
    A

    @Hcisly Oh. Thanks for the reply :)


  • 0

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


Log in to reply
 

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