zoukankan      html  css  js  c++  java
  • _leetcode-479

    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

    此题较难,我一开始没读懂题,到现在还是有些没有理解,所以下面是借鉴别人的解法。

    此题题意是求两个n位数的最大回文,n是输入,输出有些数太大所以对1337取余。什么是回文?就是数字左右两边对称,比如123321,1221,987789都是回文。

    java代码:

    public class Solution{
        public int largestPalindrome(int n) {
            long max = (long)Math.pow(10, n) - 1;
            long min = max / 10+1; 
            
            for (long h = max; h > min; h--) {
                long left = h, right = 0;
                for (long i = h; i != 0;  i /= 10){
                    right = right * 10 + i % 10;//9   99     8   89
                    left*= 10;                  //990 9900   980 9800
                }
                
                long palindrom = left + right;  //9999  9889  // construct the palindrome
                for (long i = max; i > min; i--) {
                    long j = palindrom / i;
                    if (j > i || j <= min) break;     // terminate if the other number is greater than current number or is not an n-digit number
                    if (palindrom % i == 0) return (int)(palindrom % 1337); // found if current number is a factor
                }
            }
    
            return 9;    // account for case n = 1
        }
    }
    

      

  • 相关阅读:
    详解Android Intent
    【JAVA EE企业级开发四步走完全攻略】
    撼动IT界的10大编程语言
    System.getProperty() 常用值
    Android List,Adapter相关
    为程序员量身定制的12个目标
    java 算法数据
    JAVA基础之理解JNI原理
    Java 工厂模式
    linux下C语言读取网卡MAC地址
  • 原文地址:https://www.cnblogs.com/lcbg/p/6543512.html
Copyright © 2011-2022 走看看