479. Largest Palindrome Product

来源:互联网 发布:东华软件西安分公司 编辑:程序博客网 时间:2024/06/04 20:08

1.题目
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].

2.分析
这道题理论上是不难的,但是我花了好长时间- -,一直是时间复杂度过高,不能通过全部的测试用例,最后借鉴了他人的解法,发现其实解题思路都一样,只是,双层for遍历时,条件控制不一样,少做了非常多的不必要的工作。对于输入数值n,我们结果范围应该是在最小n位数与最大n位数之间。而要寻找最大回文数,应该从后向前遍历,并记录中间结果,作为遍历结束的条件。

3.解题
我的解题:

     public 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 = toLong(i);        for(long j=maxnumber;j*j>=num;j--){            if(num%j==0){ // num已是回文数,只要mod为0就找到了结果                return (int)(num%1337);            }        }    }    return 0;}public long toLong(int number){    StringBuffer b = new StringBuffer();    String str = b.append(number).reverse().toString();    return Long.valueOf(number+str);    }

4.总结
在处理数值问题时,经常会遇到数值范围,数值大小次序,以及数值遍历的结束的处理问题,处理不当,程序就做了相当多的无用工作。而解题过程中一直遇到的时间超时的问题,有时候是解题思路存在问题,有时候是思路对了,但是程序的逻辑处理有问题,要仔细检查自己程序步骤,看是不是有一些处理压根不需要,而随着数据量的增加,会越发明显。

原创粉丝点击