479. Largest Palindrome Product

本文介绍了一种寻找由两个n位数相乘得到的最大回文数的方法,并提供了一个具体的算法实现。考虑到结果可能非常大,最终返回的是该回文数模1337的值。

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=1时,结果为9.
当n>1时,两个n位数相乘最大回文结果必然是2n位数的。
可以先构造回文,然后判断是否能够分解成2个n位数相乘。

class Solution {
    public int largestPalindrome(int n) {
        if(n == 1)
            return 9;
        int maxNumber=(int)Math.pow(10,n)-1;
        for(int i = maxNumber;i > maxNumber / 10;i--){
            long num = palindrome(i);
            for(long j = maxNumber;j * j >= num;j--){
                if(num % j==0)
                    return (int)(num % 1337);
            }
        }
        return 0;
    }
    public long palindrome(int i){
        StringBuffer s = new StringBuffer();
        s.append(Integer.toString(i)).reverse();
        return Long.parseLong(i + s.toString());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值