[刷题防痴呆] 0479 - 最大回文数乘积 (Largest

2021-10-31  本文已影响0人  西出玉门东望长安

题目地址

https://leetcode.com/problems/largest-palindrome-product/

题目描述

479. Largest Palindrome Product

Given an integer n, return the largest palindromic integer that can be represented as the product of two n-digits integers. Since the answer can be very large, return it modulo 1337.

 

Example 1:

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

Input: n = 1
Output: 9

思路

关键点

代码

class Solution {
    public int largestPalindrome(int n) {
        if (n == 1) {
            return 9;
        }
        int mod = 1337;
        int min = (int) Math.pow(10, n - 1);
        int max = (int) (Math.pow(10, n)) - 1;
        
        for (int i = max; i >= min; i--) {
            String temp = Integer.toString(i);
            StringBuffer sb = new StringBuffer();
            sb.append(temp);
            String reverse = sb.reverse().toString();
            long product = Long.valueOf(temp + reverse);
            for (long j = max; j * j >= product; j--) {
                if (product % j == 0) {
                    return (int)(product % mod);
                }
            }
        }
        
        return -1;
    }
}
上一篇下一篇

猜你喜欢

热点阅读