zoukankan      html  css  js  c++  java
  • [LeetCode] 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.

    Example:

    Input: 2

    Output: 987

    Explanation: 99 x 91 = 9009, 9009 % 1337 = 987

    Note:

    The range of n is [1,8].

     先找出符合位数的回文数,然后对回文数进行判断能否由两个n位数相乘。最后将符合条件的回文数整除。

    class Solution {
    public:
        int largestPalindrome(int n) {
            if (n == 1)
                return 9;
            long maxVal = pow(10, n) - 1;
            long minVal = maxVal / 10;
            for (long i = maxVal; i >= minVal; i--) {
                long val = createPalindrome(i);
                for (int j = maxVal; j >= minVal; j--) {
                    if (val / j > maxVal) {
                        break;
                    }
                    if (val % j == 0) {
                        return static_cast<int>(val % 1337);
                    }
                }
            }
            return 0;
        }
        
        long createPalindrome(long num) {
            long tmp = num;
            long a = 0;
            int n = 0;
            while(tmp) {
                a = a * 10 + tmp % 10;
                n++;
                tmp /= 10;
            }
            while(n) {
                num = num *10;
                n--;
            }
            return num + a;
        }
    };
    // 1354 ms

    Trick algorithm:

    class Solution {
    public:
        int largestPalindrome(int n) {
            vector<long> pattern{9, 9009, 906609, 99000099, 9966006699, 999000000999, 99956644665999, 9999000000009999};
            return static_cast<int>(pattern[n - 1] % 1337);
        }
    };
    // 0 ms
  • 相关阅读:
    二叉树的非递归遍历
    关于vc变量定义顺序猜测
    单点登录详解(token简述)(七)
    session及cookie详解(七)
    dubbo(八)
    Zookeeper简介(九)
    拦截器与过滤器的区别(九)
    cookie详解(八)
    kafka可视化工具(二)
    Windows环境安装kafka(一)
  • 原文地址:https://www.cnblogs.com/immjc/p/8214063.html
Copyright © 2011-2022 走看看