Largest Palindrome Product

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].

    public class Palindrome {
        public static void main(String[] args) {
            for (int n = 1; n <= 8; n++) {
                System.out.println(Solution.largestPalindrome(n));
            }
        }

        public static class Solution {
            public static int largestPalindrome(int n) {
                if (n == 1) {
                    return 9;
                }
                int high = (int) Math.pow(10D, n * 1D) - 1;
                int low = high / 10;
                for (int i = high; i > low; i--) {
                    long palindrome = getPalindrome(i);
                    for (long j = high; j > low; j--) {
                        if (palindrome / j > high) {
                            break;
                        }
                        if (palindrome % j == 0) {
                            return (int) (palindrome % 1337);
                        }
                    }
                }
                return -1;
            }

            private static long getPalindrome(int num) {
                return Long.parseLong(num + (new StringBuilder(String.valueOf(num))).reverse().toString());
            }
        }

    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,358评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,545评论 0 23
  • 说起拍照,不论是用什么设备傻瓜相机、数码相机、单反相机还是现在更流行的手机自拍,除了与拍照的技术有关,拍照还需要摆...
    小铃铛ring阅读 6,828评论 2 0
  • 我是日记星球226号星宝宝,我正在参加21天蜕变之旅第七期,这是我第63篇原创日记。二十年的大型三甲医院工作经历让...
    天鸣老师阅读 3,870评论 8 4
  • 今天一早,哥哥起床第一件事就是“妈,今天是弟弟生日!” “李昊同,生日快乐!”听,满屋都是哥哥的祝福声,弟...
    李昊同阅读 3,576评论 0 0

友情链接更多精彩内容