Fastest Java Solution with 92ms


  • 0
    A

    I have optimized one existing solution and it now changed from 173 ms to 92ms.
    Simply removed Math.pow & StringBuffer reverse process to calculate palindromic Number.

    public class Solution {
        // optimizing speed ; removing Math.pow from upperLimit
        public long[] maxLimits = new long[]{
            10,100,1000,10000,100000,1000000, 10000000, 100000000
        }; 
        
        public int largestPalindrome(int n) {
    if (n == 1) return 9;
            
            int high = (int) maxLimits[n-1]-1;
            int low = (int) maxLimits[n-2];
            for (int i = high; i >= low; i--) {
                long palindrome = PalindromNum(i);
                int hi = high;
                while (hi % 11 != 0) {
                    hi--;
                }
                for (int j = hi; j >= low; j -= 11) {
                    if (palindrome / j > high) {
                        break;
                    }
                    if (palindrome % j == 0) {
                        return (int) (palindrome % 1337);
                    }
                }
            }
            return 0;
        }
    
    // calculate Palindromic
        public long PalindromNum(int x) {
            long out = x;
            while(x > 0) {
                out = (10*out)+(x%10);
                x = x/10;
            }
            return out;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.