LeetCode: 479. Largest Palindrome Product

来源:互联网 发布:最小截图软件下载 编辑:程序博客网 时间:2024/06/03 10:56

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位数相乘得到的回文数字,结果对1337取余。

分析:当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--){//从大到小遍历n位数            long num=palindrome(i);//构造回文            for(long j=maxNumber;j*j>=num;j--){//判断num是否可以分解为两个n位数相乘                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());    }}
原创粉丝点击