This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int largestPalindrome(int n) { | |
long long minNum = static_cast<long>(pow(10, n - 1)), maxNum = static_cast<long>(pow(10, n) - 1), div = static_cast<long>(pow(10, n)); | |
//get first half of palindrome | |
long long lo = minNum * minNum / (div / 10), hi = maxNum * maxNum / div; | |
if (n == 1)return 9; | |
while (hi >= lo) | |
{ | |
long long palin = getPalindrome(hi); | |
for (long long i = maxNum; i >= minNum; --i) | |
{ | |
//no reason to check the number less than palin / maxNum or sqrt(palin) | |
if(palin / i > maxNum || i * i < palin)break; | |
if (!(palin % i)) | |
return palin % 1337; | |
} | |
--hi; | |
} | |
return -1; | |
} | |
private: | |
long long getPalindrome(long long num) | |
{ | |
long n = num, rev = 0; | |
while (n) | |
{ | |
long digit = n % 10; | |
rev = rev * 10 + digit; | |
n /= 10; | |
num *= 10; | |
} | |
return num + rev; | |
} | |
}; |
No comments:
Post a Comment