​LeetCode刷题实战479:最大回文数乘积

程序IT圈

共 1709字,需浏览 4分钟

 ·

2021-12-28 13:45

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 最大回文数乘积,我们先来看题面:
https://leetcode-cn.com/problems/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.


你需要找到由两个 n 位数的乘积组成的最大回文数。
由于结果会很大,你只需返回最大回文数 mod 1337得到的结果。

示例                         

示例:

输入: 2
输出: 987
解释: 99 x 91 = 9009, 9009 % 1337 = 987

说明:
n 的取值范围为 [1,8]。


解题

举个例子:
max = 99;
从i= 98开始循环
构造出回文数 rev = 9889
对于 x = 99 ,rev不能整除,继续
对于 x = 98 , 98 * 98 = 9604,小于rev,退出第二层循环
...
...
直到i= 90
构造出回文数9009

class Solution {
      public int largestPalindrome(int n) {
        if(n == 1) return 9;
        long max = (long)Math.pow(10,n) - 1;
        for(long i = max - 1; i > max / 10; i--){
            String s1 = String.valueOf(i);
            long rev = Long.parseLong(s1 + new StringBuilder(s1).reverse().toString());
            for(long x = max; x * x >= rev; x --){
                if(rev % x == 0) return (int)(rev % 1337);
            }
        }
        return -1;
    }
}


好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-460题汇总,希望对你有点帮助!

LeetCode刷题实战461:汉明距离

LeetCode刷题实战462:最少移动次数使数组元素相等 II

LeetCode刷题实战463:岛屿的周长

LeetCode刷题实战464:我能赢吗

LeetCode刷题实战465:最优账单平衡

LeetCode刷题实战466:统计重复个数

LeetCode刷题实战467:环绕字符串中唯一的子字符串

LeetCode刷题实战468:验证IP地址

LeetCode刷题实战469:凸多边形

LeetCode刷题实战470:用 Rand7() 实现 Rand10()

LeetCode刷题实战471:编码最短长度的字符串

LeetCode刷题实战472:连接词

LeetCode刷题实战473:火柴拼正方形

LeetCode刷题实战474:一和零

LeetCode刷题实战475:供暖器

LeetCode刷题实战476:数字的补数

LeetCode刷题实战477:汉明距离总和


浏览 19
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报