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


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