479. Largest Palindrome Product
java
注意数值类型!(int) (pro%m)code
public class Solution{ public static void main(String[] args){ Solution s = new Solution(); s.largestPalindrome(2); } public int largestPalindrome(int n) { if(n==1) return 9; //int h = reserve(87); int m = 1337; int mod = (int) Math.pow(10, n); int max = (int) Math.pow(10, n) - 1; long pro = (long)max * (long)max; int left = (int) (pro/mod); int right = (int) (pro%mod); if(left==reserve(right,n)) return (int)(pro%m); if(left>reserve(right,n)) left--; pro = (long)left*(long)mod+ (long)reserve(left,n); while(left!=mod/10){ for(int i=max;i>pro/i;i--){ if(pro%i==0) return (int) (pro%m); } left--; pro = (long)left*(long)mod+ (long)reserve(left,n); } return (int) (pro%m); } /* private int reserve(int n, int dig){ int x = n; int res = 0; int ten = (int)Math.pow(10,dig-1); while(x != 0 ){ int d = x%10; res+=ten*d; ten/=10; x/=10; } return res; } */ private int reserve(int num, int n) { // TODO Auto-generated method stub int res =0; for(int i=0;i<n;i++){ int h = num%10; res += h*(int)Math.pow(10, n-i-1); num = num/10; } return res; } }