leetcode 479. Largest Palindrome Product最大的迴文乘積__leetcode

來源:互聯網
上載者:User

問題描述:

  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為其他值時,最大的迴文數都是偶數,所以可以利用字串反轉來得到所有的迴文數。

得到迴文數後,需要檢查此迴文數是否可以由兩個數相乘得到(即,使此數依次除以某n位元,看餘數是否為0)。若進行除法運算後,商大於n位元的最大值,則跳出此次迴圈,繼續尋找下一個迴文數。

技巧: 利用StringBuffer類,可以利用reverse()方法直接進行翻轉; 尋找迴文數時,從最大數開始,這樣可以減少時間複雜度。

代碼:

class Solution {    public int largestPalindrome(int n) {        if(n == 1)            return 9;        int upper = (int)Math.pow(10,n)-1;        for(int i = upper; i>upper/10; i--){            long palin = toPalindrome(i);            for(int j = upper; j>upper/10; j--){                if(palin / j > upper)                    break;                if(palin % j == 0)                    return (int)(palin % 1337);            }        }        return -1;            }    public long toPalindrome(int i){        StringBuffer str = new StringBuffer();        str.append(i+"");        String a = str.reverse().toString();        return Long.parseLong(i+""+a);    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.