1216. Largest Palindrome Product

描述

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.

  1. The range of n is [1,8].
您在真实的面试中是否遇到过这个题?  

样例

Input: 2
Output: 987
Explanation: 99 x 91 = 9009, 9009 % 1337 = 987

我认为这个题有点蹊跷,如果遍历的话,会超时,然后翻看了大佬们的解法,最屌的解法叫做查表法,直接把答案列出来就好了。参考了大佬的解法:

http://www.cnblogs.com/grandyang/p/7644725.html

这种解法就是限制了一些条件范围,制造了回文数而不是判断,第二步循环的时候,判断的是平方数,因为每次都是递减,所以平方比制造的回文数小的话,后面的数就不必验证了。

class Solution {
public:
    /**
     * @param n: the number of digit
     * @return: the largest palindrome mod 1337
     */
    int largestPalindrome(int n) {
        // write your code here
        int upper = pow(10, n) - 1, lower = upper / 10;
        for (int i = upper; i > lower; --i) {
            string t = to_string(i);
            long p = stol(t + string(t.rbegin(), t.rend()));
            for (long j = upper; j * j > p; --j) {
                if (p % j == 0) return p % 1337;
            }
        }
        return 9;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章